Variables & types

Variables are PHP-style: start with $, no declaration keyword, inferred types. Add an explicit type after the name when you want one.

$count = 5;                  // inferred int
$pi = 3.14159;               // float
$ok = true;                  // bool
$who = "Ada";              // string

$count: int = 5;             // pinned types
$rate: float = 0.19;
$name: string = "Ann";
$flag: bool = false;

$items = [1, 2, 3];          // list array
$user = ["name" => "Ada",  // map array (string keys)
         "lang" => "HolyPHP"];
TypeLiteralsNotes
int42, 0x2A64-bit signed
i128332825110087067562321196029789634457848128-bit signed; wider literals get this type
float3.14, 1e964-bit IEEE
booltrue / false
string"..." with {$var} interpolationimmutable, refcounted
array[1, 2], ["k" => "v"]copy-on-write value semantics
mixedanythingruntime-tagged hval

i128 is a native 128-bit signed integer. It widens from int and the sized integer spellings implicitly, in assignments, arguments, returns and mixed arithmetic (the result stays i128). Narrowing back to int needs an explicit cast; (i128) itself converts from int, float, string and other integers. Arithmetic, comparisons, the spaceship operator, bit operations and shifts all work; / and % are integer division and modulo (unlike int / int, which yields a float), and dividing by zero throws. Overflow wraps like int.

$big = (i128)1 << 100;            // 1267650600228229401496703205376
echo $big * 2;                  // 2535301200456458802993406410752
echo strval($big);              // full decimal value
$back = (i128)"-77";            // from a string
$narrow = (int)$big;            // only an explicit cast narrows

An i128 does not fit into an array, a map, a mixed slot or a closure (those hold a 64-bit runtime value). Storing one there is a compile error rather than a silent truncation: convert with (int) or strval() first. echo, concatenation, templates, strval(), print_r, var_dump and json_encode (as a JSON number) print the full value.

Functions

Fully typed signatures with optional parameters and defaults. Untyped functions are inferred like scripts.

function greet(string $who): string {
    return "Hi, {$who}!";
}

function pow2(float $base, int $exp = 2): float {
    return $base ** $exp;
}

// by-reference parameter (a mutable borrow)
function bump(int &$r): void { $r += 1; }

$n = 41;
bump($n);        // $n === 42

An &$r parameter aliases the caller's variable: the callee writes through it and the call site sees the new value. The argument must be a variable the compiler can alias, and it may live in any of the shapes a variable takes here — a local, a global, a slot a closure captured with use (&$x), or another by-reference parameter.

function anonymize(mixed &$who): void { $who = "nobody"; }

$user = "Elias";
$seen = function() use (&$user): void { anonymize($user); };  // boxed capture
$seen();
echo $user;      // nobody

function total(array &$bag): void { $bag[] = 3; }

$bag = [1, 2];
total($bag);     // $bag === [1, 2, 3]
What is not aliased: a by-reference argument has to be a variable (“bump(1 + 1)” is an error, not a silent copy), a closure cannot declare one (its arguments arrive boxed — capture with use (&$x) instead), and a by-reference parameter cannot itself be captured by reference, since that would need a write-back the compiler does not emit yet. Each of those is a compile error naming the line, never a wrong answer.

Operators

GroupOperators
Arithmetic+ - * / % **
String. concat, .= append
Comparison== != === !== < > <= >= <=>
Logic&& || !
Bitwise& | ^ << >>
Null coalesce??
Compound+= -= *= /= %= .= **=
Increment++ -- (prefix and postfix)
Ternarycond ? a : b

Control flow

if ($n < 2) { return $n; }
elseif ($n == 2) { echo "two"; }
else { echo "many"; }

while ($i < 10) { $i++; }

for ($i = 0; $i < 10; $i++) { echo $i; }

foreach ($nums as $x) { $total += $x; }
foreach ($user as $k => $v) { echo "{$k} => {$v}"; }

match — algebraic switching

function classify(int $n): string {
    return match ($n) {
        0 => "zero",
        1, 2, 3 => "small",
        _ => "big",
    };
}

Classes & OOP

Visibility is explicit: pub (public), private, static for fields. Methods inherit PHP-style; constructors may be inherited too.

class Counter {
    pub int $count = 0;          // field with default
    private $secret = "s";

    pub function __construct(int $start = 0) {
        $this->count = $start;
    }
    pub function bump(): void {
        $this->count += 1;
    }
    pub function get(): int {
        return $this->count;
    }
}

$c = new Counter(10);
$c->bump();
echo $c->get();      // 11
class Animal {
    pub function speak(): string { return "..."; }
}
class Dog extends Animal {
    pub function speak(): string { return "Woof!"; }
}
echo (new Dog())->speak();   // "Woof!" — dynamic dispatch

Closures & captures

Closures capture PHP-style with use. By-value copies by default; use (&$x) captures by reference — the variable lives in a heap box shared with the outer scope.

$base = 100;
$addBase = function(int $x) use ($base): int {   // by value
    return $base + $x;
};

$clicks = 0;
$onClick = function() use (&$clicks): void {     // by reference
    $clicks = $clicks + 1;                       // outer $clicks changes
};
$onClick(); $onClick();
echo $clicks;    // 2
Why it's safe: the compiler boxes the captured variable and forces it to mixed, so the same slot is shared — no dangling pointers, no data races, verified by hphp check.

Exceptions

try {
    throw "boom";
} catch (string $e) {
    echo "caught: {$e}";
} finally {
    echo "always runs";
}

throw accepts a value (strings today, Exception objects too). Handlers are invoked through a setjmp-free architecture — the runtime runs each protected block as a helper, so no volatile tricks appear in generated code and -O2 is safe.

Enums

enum Farbe: int { Rot, Gruen, Blau }

function colorName(Farbe $f): string {
    return match ($f) {
        Farbe::Rot   => "red",
        Farbe::Gruen => "green",
        Farbe::Blau  => "blue",
    };
}

Memory model

HolyPHP checks ownership and supported borrow patterns at compile time. The checker is still a subset of Rust's borrow checker; dynamic values, aliases and unsafe code have additional limits.

ConceptSyntaxMeaning
Value semanticsplain assignmentscalars & arrays copy-on-write
Immutable borrow&$xread-only alias, many allowed
Mutable borrow&mut $xexactly one at a time
Owned boxown<T>exclusive ownership, moves
Shared pointerRc<T>shared ownership syntax backed by the reference-counting runtime
Weak propertypublic weak Node $parent;non-owning nullable reference; reads as Node?
Raw pointer*T / &$x under unsafeonly inside unsafe {}
Memory safety modedeclare(enforce_memory_safety=1);rejects unsafe blocks and calls to builtins marked unsafe
// borrow checker at compile time:
function laenge(string $text): int {     // takes an immutable borrow
    return strlen($text);
}
$w = "borrowed";
echo laenge($w);        // owner keeps $w

// this is a compile ERROR (two mutable borrows):
// function bump(int &$r): void { $r += 1; }
// bump(&$n); bump(&$n); ...  => rejected by hphp check
unsafe {
    $geheim: int = 42;
    $zeiger: &int = &$geheim;      // raw pointer
    echo "deref = " . (*$zeiger);
}
unsafe: raw pointer operations need an unsafe block. The compiler cannot guarantee memory safety for code that uses raw pointers or escapes the supported borrow rules.

Use declare(enforce_memory_safety=1); at the start of a file to make unsafe blocks and calls to builtins marked unsafe compile errors. The declaration applies to the whole file, and the borrow checker analyzes the file's script and functions. Both this mode and ordinary code use the same reference-counted value representation.

Runtime memory: generated owners retain and release strings, arrays, closures, and class instances. Arrays detach on mutation when shared. Strong cycles across objects, arrays, and closures are collected automatically. A weak property does not keep its target alive; it reads as a nullable value and becomes null after collection. See the memory model guide for ownership rules and remaining limits.

Runtime cost: before a program starts a thread, reference counts use a single-thread path and cycle-collector registry operations avoid the mutex. Starting a thread switches those operations to synchronized mode. Generated string-literal sites cache their handle after first use, and owner cleanup registrations reuse a per-thread buffer. In safety mode, parameters used only by read-only builtins such as count(), array_sum(), and strlen(), or forwarded to another proven borrowing parameter, can omit the call-boundary retain/release pair. Unknown calls, writes, returns, stores, methods, and closures keep the normal RC path. A function-local array made from scalar literals also uses a short-lived arena when every use is read-only; returning, storing, or mutating it keeps normal ownership. In canonical counted loops, the same proof can also remove array index checks when the body only passes the stable array to a proven borrower. Safety mode also uses reusable iteration regions for local scalar arrays and strings whose uses stay inside the loop, including method bodies. Calls on concrete class receivers may borrow direct local arguments when every reachable override proves the parameter read-only and nonescaping. Interface or unknown dispatch keeps normal reference counting.

Unsafe pointers: raw addresses are integers outside the managed-object reference-count path. memset() and memcpy() return their input address; stream_recv() copies data out of reusable io_uring buffers before returning an owned string. Builtin temporary cleanup respects borrowed results and immortal string literals.

Indexing: array-list and string reads check their bounds at runtime. An out-of-range read raises a catchable error ("Array index out of bounds" or "String index out of bounds"). Map lookups for absent keys continue to return null. The compiler removes checks in a canonical counted loop when it proves the array and induction variable are stable; in safety mode the body may also pass the array to a proven borrower; other reads retain runtime checks. foreach uses a runtime iterator. array_sum() promotes to a float if adding integer elements would overflow int64.

Threads: captured values and channel payloads move across the thread boundary, so later use of a moved source is a compile error. Immutable scalar and string values may be shared; arrays and maps move when their contents are safe value types and keep copy-on-write behavior. Ordinary mutable objects cannot be sent through channels. Known closures are checked at the boundary, including indirect callbacks typed as thread_callable. The bundled Thread and Pool wrappers use the same checks. See the memory model guide for the proof limits.

Imports & the stdlib

Libraries ship inside the compiler binary — import finds them with no files on disk. A spec without an extension names a library or package; with .hphp it means a file next to the importing source.

import "ui";        // desktop GUI toolkit (embedded)
import "websocket"; // RFC 6455 server (embedded)
import "async";     // event loop + HTTP (embedded)
import "thread";    // OS threads + channels (embedded)
import "helpers";     // helpers.hphp next to this file

Strings

Immutable and refcounted; interpolation is compile-time parsed into concat calls.

$name = "Ada";
echo "Hi {$name}, you have " . (3 + 4) . " new messages";

$s = "Hello";
$s .= " World";          // append (rebuilt behind the scenes)

Arrays & maps

One type for both: lists keep insertion order; assigning a string key or a non-sequential int key promotes to a keyed map (exactly PHP's semantics).

$nums = [5, 3, 8, 1, 9];
$nums[] = 7;                 // append
sort($nums);                 // in place
echo $nums[0];               // 1

$m = [];
$m[1] = "a";                 // key 1 is remembered
$m["name"] = "Ada";        // becomes a keyed map
foreach ($m as $k => $v) {
    echo "{$k} => {$v}";   // 1 => a, then name => Ada
}

$a = [1, 2, 3];
$b = $a;                     // COW: shares until one writes
$b[0] = 99;                  // clones now; $a unchanged

Strings (90 functions)

Everything around byte strings: searching, cutting, comparing, padding, formatting and escaping. Strings are byte-oriented (UTF-8 text passes through untouched, but length/count are bytes).

strlen(string|array $v): int
Length of a string in bytes (not characters). For arrays use count().
strtoupper(string $s): string
Converts every ASCII letter in the string to uppercase.
strtolower(string $s): string
Converts every ASCII letter in the string to lowercase.
ucfirst(string $s): string
Uppercases the first character of the string, leaves the rest untouched.
lcfirst(string $s): string
Lowercases the first character of the string, leaves the rest untouched.
trim(string $s): string
Strips leading and trailing whitespace (space, tab, newline, CR, NUL).
ltrim(string $s): string
Strips leading whitespace only. Optional second argument: character list to strip.
rtrim(string $s): string
Strips trailing whitespace only. Alias: chop(). Optional second argument: character list.
strrev(string $s): string
Reverses the string byte by byte.
str_repeat(string $s, int $n): string
Repeats the string n times: str_repeat("ab", 3) -> "ababab".
str_pad(string $s, int $len[, string $pad]): string
Pads the string to the given length with a pad string (default " "), repeated on the right.
str_replace(string $search, string $replace, string $subject): string
str_replace($search, $replace, $subject) — replaces every occurrence of $search in $subject.
substr(string $s, int $start[, int $len]): string
substr($s, $start[, $len]) — extracts up to $len bytes starting at $start. Negative $start counts from the end; omitted $len means "to the end".
strstr(string $haystack, string $needle): mixed
Returns the part of $haystack from the first occurrence of $needle to the end, or false if not found.
strchr(string $haystack, string $needle): mixed
Alias of strstr().
strpos(string $haystack, string $needle): mixed
Byte position of the first occurrence of $needle in $haystack, or false when absent. Use !== false to test.
str_contains(string $haystack, string $needle): bool
true when $needle occurs anywhere in $haystack (PHP 8 style, no position needed).
str_starts_with(string $haystack, string $needle): bool
true when $haystack begins with $needle.
str_ends_with(string $haystack, string $needle): bool
true when $haystack ends with $needle.
strcmp(string $a, string $b): int
Byte-wise comparison: returns < 0, 0, or > 0 as $a sorts before, equal to, or after $b.
strncmp(string $a, string $b, int $n): int
Like strcmp() but compares at most the first n bytes (third argument).
strncasecmp(string $a, string $b, int $n): int
Case-insensitive strncmp(): first n bytes, returns -1/0/1 style result.
strcasecmp(string $a, string $b): int
Case-insensitive strcmp().
explode(string $separator, string $s): mixed
explode($separator, $s) - splits the string at every separator into an array. An empty separator splits into single characters (UTF-8 safe): explode("", "Hilf") -> ["H","i","l","f"].
implode(string $glue, array $arr): string
Joins array elements with a glue string: implode($glue, $arr) or implode($arr).
join(string $glue, array $arr): string
Alias of implode().
nl2br(string $s): string
Inserts "<br />" before every newline. Newlines are kept.
number_format(float|int $num[, int $decimals, string $dec_point, string $thousands_sep]): string
Formats a number with grouped thousands: number_format($n[, $decimals[, $dec_point, $thousands_sep]]). Defaults: 0 decimals, ".", ",".
password_hash(string $password): string
Creates a salted password hash ($hphp$4096$salt$digest, PBKDF2-SHA256, 4096 rounds). Store this string; never store plain passwords.
password_verify(string $password, string $hash): bool
password_verify($plain, $hash) — recomputes the digest with the hash's salt and compares timing-safely. true when the password matches.
strtotime(string $s): int
Parses a date/time string ("2024-03-15 12:30:00", "2024-03-15", "12:30:00") into a Unix timestamp; 0 on failure.
parse_url(string $url): mixed
parse_url($url) — map with scheme, user, host, port, path, query, fragment; missing parts are empty strings, port defaults to 80/443.
urlencode(string $s): string
Encodes a string for use in a query string: space becomes +, reserved chars become %XX.
urldecode(string $s): string
Inverse of urlencode().
htmlentities(string $s): string
Converts & " ' < > (and more) to their HTML entities so the string is safe to embed as text.
htmlspecialchars(string $s): string
Converts only the five HTML-critical characters & " ' < > to entities.
sprintf(string $format, mixed ...$args): string
printf-style formatting that returns the string. Supports %d %s %f %x %o %b %e %c, width, precision and "-" left-align.
printf(string $format, mixed ...$args): int
Like sprintf() but prints the result and returns its length.
vsprintf(string $format, array $args): string
sprintf() with the arguments taken from an array.
ord(string $s): int
Byte value of the first character of the string (0–255).
chr(int $n): string
One-character string for the given byte value.
bin2hex(string $s): string
Hexadecimal representation of the bytes, two chars per byte: bin2hex("AB") → "4142".
hex2bin(string $s): string
Decodes a hexadecimal string back into raw bytes.
str_split(string $s[, int $len]): mixed
str_split($s[, $len]) - cuts the string into chunks of $len characters (default 1) and returns them as an array.
ucwords(string $s): string
Uppercases the first letter of every whitespace-separated word.
wordwrap(string $s, int $width[, string $break]): string
Wraps a string to a given width by inserting breaks (default "\n") at word boundaries.
similar_text(string $a, string $b): int
Number of matching characters between the two strings (a rough similarity measure).
levenshtein(string $a, string $b): int
Edit distance (insertions, deletions, substitutions) between the two strings.
substr_count(string $haystack, string $needle): int
Counts how many times $needle occurs in $haystack.
str_shuffle(string $s): string
Randomly shuffles the characters of the string (not cryptographically secure).
strip_tags(string $s[, string $allowed]): string
Removes HTML and PHP tags from the string.
html_entity_decode(string $s): string
Inverse of htmlentities(): "&amp;" becomes "&" again.
is_string(mixed $v): bool
true when the value is a string.
strval(mixed $v): string
Converts the value to its string representation.
stream_socket_server(string $addr): mixed
stream_socket_server("host:port") — binds and listens on a TCP socket; returns a server handle (or -1).
stream_socket_client(string $addr): mixed
stream_socket_client("host:port") — connects to a TCP server; returns a socket handle (or -1).
stream_socket_accept(resource $server): mixed
Accepts one incoming connection from a server handle (blocks until a client arrives).
stream_socket_accept2(resource $server, int $timeout_ms): mixed
Like stream_socket_accept() but with a timeout in milliseconds.
stream_set_blocking(resource $sock, bool $blocking): bool
Switches a socket handle between blocking and non-blocking mode.
stream_ready(array $handles): mixed
Checks which of the given socket handles are readable (select-style); returns the ready handles as an array.
stream_recv(resource $sock[, int $max]): string
stream_recv($sock[, $max]) - receives up to $max bytes (default 4096) from the socket as a string. In direct io_uring mode the string borrows the ring buffer and is only valid until the next recv or stream_recv_release on that socket; copy it to keep it.
stream_send(resource $sock, string $data): int
stream_send($sock, $data) — sends the string over the socket; returns the bytes sent.
stream_eof(resource $sock): bool
true when the peer closed the connection.
stream_peer(resource $sock): string
IP:port of the remote end of the socket.
stream_close(resource $sock): bool
Closes a socket handle.
ui_browser_html(...$args): int
ui_browser_html($b, $html) — shows a document directly instead of loading a URL.
ui_browser_url(...$args): string
Current URL of the page.
thr_join(...$args): mixed
thr_join($tid) — waits for a spawned thread; true when it was still joinable.
json_str_field(string $j, string $key): string
Reads one string field of a flat JSON object without a full parse.
sb_json_str(int $h, string $s): int
Appends a JSON-escaped copy of a string.
str_at_eq(string $s, int $start, int $len, string $lit): bool
Compares len bytes at start with a literal without building a substring.
str_find_range(string $s, string $needle, int $start): int
Finds a needle in a string starting at an offset and returns its byte index, or -1.
str_free(...$args): bool unsafe
Unsafe: frees a string early. Only call it on a value you own; a second call, or freeing a borrowed string, is a use-after-free.
str_from_bytes(int $p, int $n): string unsafe
Unsafely copies len bytes from a raw address into a new string.
str_int_range(string $s, int $start, int $end): int
Alias of str_to_int_range(): decimal integer in a byte range.
str_persist(string $s): string
Returns a string that outlives the current request scope. Identity in this core (strings are plain heap blocks).
str_pos_ci(string $s, string $needle, int $start): mixed
Case-insensitive byte search from an offset; returns the index or false.
str_prefix_ci(string $s, string $prefix): mixed
Case-insensitive prefix test.
str_to_int(string $s): int
Parses the whole string as a decimal integer (0 when it is not one).
str_to_int_range(string $s, int $start, int $end): int
Runtime support builtin ported with the io_uring/SQLite modules.
str_trim_range(string $s, int $start, int $end): mixed
Trims ASCII whitespace inside [start,end) without building a substring and returns the trimmed bytes.
stream_ready_into(...$args): bool unsafe
Unsafe: waits until any of the handles is readable, resets the caller's array in place and appends the ready handles.
stream_recv_release(...$args): int
Releases the receive buffer of a connection back to the runtime pool. In direct io_uring mode every string returned by stream_recv since the last release becomes invalid, so copy what you keep.
stream_send2(...$args): int
Blocking variant of stream_send2_nb.
stream_send2_nb(...$args): int
Non-blocking writev of two buffers: bytes written, -1 would block, -2 error.
stream_send_nb(...$args): int
Non-blocking send: bytes written, -1 would block, -2 error.
stream_send_sb(...$args): int
Sends a whole string-builder response without copying it and consumes the builder.
stream_set_nodelay(...$args): bool
Disables Nagle on a connected socket (accepted sockets inherit it on Linux).
stream_set_socket_buffers(...$args): bool
Sets TCP receive/send buffer sizes on a listening or connected socket (0 = kernel default).
stream_socket_server_reuseport(...$args): int
Creates a listening SO_REUSEPORT socket (one of N accepts the connection).

Math (35 functions)

Arithmetic helpers, trigonometry (radians!), rounding with PHP_ROUND_HALF_* modes, and randomness. rand()/mt_rand() are fine for games and shuffling; use random_int()/random_bytes() for anything security-related.

random_bytes(int $n): string
random_bytes($n) — $n cryptographically secure random bytes as a raw binary string (max 1024).
max(mixed ...$args): mixed
Largest of the given numbers or array elements (variadic).
min(mixed ...$args): mixed
Smallest of the given numbers or array elements (variadic).
rand([int $min, int $max]): int
rand() → pseudo-random int, or rand($min, $max) within the inclusive range (not secure).
mt_rand([int $min, int $max]): float
Mersenne-Twister pseudo-random: mt_rand() or mt_rand($min, $max) (faster, still not secure).
srand(int $seed): void
Seeds rand() — only useful to get reproducible sequences.
mt_srand(int $seed): void
Seeds mt_rand() — only useful to get reproducible sequences.
random_int(int $min, int $max): int
Cryptographically secure random integer in [$min, $max]. Prefer this over rand().
abs(int|float $number): mixed
Absolute value; keeps the input type (int stays int, float stays float).
round(float|int $num[, int $precision, int $mode]): mixed
round($n[, $precision[, $mode]]) — rounds to $precision decimals (default 0). $mode: PHP_ROUND_HALF_UP (default), _HALF_DOWN, _HALF_EVEN, _HALF_ODD.
floor(float|int $number): float
Largest integer value ≤ $n, returned as float.
ceil(float|int $number): float
Smallest integer value ≥ $n, returned as float.
sqrt(float|int $number): float
Square root as float.
pow(float|int $base, float|int $exp): mixed
pow($base, $exp) — $base raised to $exp.
intdiv(int $a, int $b): int
Integer division truncating toward zero: intdiv(7, 2) === 3.
fmod(float|int $x, float|int $y): float
Floating-point remainder of $x / $y.
sin(float|int $number): float
Sine of the angle in radians.
cos(float|int $number): float
Cosine of the angle in radians.
tan(float|int $number): float
Tangent of the angle in radians.
atan(float|int $number): float
Arctangent in radians.
atan2(float|int $y, float|int $x): float
Angle of the point (y, x) — note the argument order.
asin(float|int $number): float
Arcsine in radians.
acos(float|int $number): float
Arccosine in radians.
log(float|int $number[, float|int $base]): float
Natural logarithm (ln). Optional second argument is the base.
log2(float|int $number): float
Binary logarithm (base 2).
log10(float|int $number): float
Common logarithm (base 10).
exp(float|int $number): float
e raised to the given power.
is_nan(float $number): bool
true for the special Not-a-Number float value.
is_finite(float $number): bool
true when the float is neither infinite nor NaN.
is_infinite(float $number): bool
true for ±infinity.
pi(): float
Returns π as float. The constant M_PI is equivalent.
deg2rad(float|int $number): float
Converts degrees to radians.
rad2deg(float|int $number): float
Converts radians to degrees.
hypot(float|int $x, float|int $y): float
hypot($a, $b) — length of the hypotenuse sqrt(a² + b²), overflow-safe.
lcg_value(): float
Pseudo-random float in [0, 1) from the combined linear congruential generator (not secure).

Arrays (69 functions)

One array type covers lists and maps (string keys allowed). The in-place sorts (sort, ksort, usort, …) modify the array and return true. Closures passed to map/filter/reduce/walk/usort are normal fn() closures.

count(array|string $v): int
Number of elements in an array, or length of a string. Aliased by sizeof().
sizeof(array|string $v): int
Alias of count(): elements in an array, bytes in a string.
array(mixed ...$args): mixed
Creates an array from the given values (or "key" => value pairs). Usually written as the [...] literal instead.
array_keys(array $a): mixed
Returns all keys of the array as a new list array.
array_values(array $a): mixed
Returns all values of the array as a freshly indexed list (0..n-1).
array_merge(array ...$args): mixed
Merges two or more arrays; later arrays overwrite string keys of earlier ones, numeric keys are appended.
array_slice(array $a, int $offset[, int $length]): mixed
array_slice($arr, $offset[, $length]) — extracts a section of the array. Negative $offset counts from the end.
array_reverse(array $a): mixed
Returns the array with elements in reverse order.
array_sum(array $a): mixed
Sum of all numeric values in the array (non-numerics count as 0).
array_product(array $a): mixed
Product of all numeric values in the array.
array_unique(array $a): mixed
Removes duplicate values, keeping the first occurrence of each.
in_array(mixed $needle, array $haystack): bool
in_array($needle, $haystack) — true when the value occurs in the array.
array_key_exists(string|int $key, array $a): bool
true when $key exists in the array (also for string keys and null values).
range(int $start, int $end): mixed
range($start, $end) — list of integers from $start to $end inclusive (also counts down).
compact(string ...$args): mixed
Builds an array from the named local variables: compact("a", "b") → ["a" => $a, "b" => $b].
array_column(array $rows, string $col): mixed
array_column($rows, $col) — picks one column out of an array of maps, indexed 0..n.
array_chunk(array $a, int $size): mixed
array_chunk($arr, $size) — splits the array into chunks of at most $size elements.
array_pad(array $a, int $size, mixed $value): mixed
array_pad($arr, $size, $value) — grows the array to $size by filling with $value (negative size pads left).
array_replace(array ...$args): mixed
array_replace($a, $b, …) — elements of later arrays overwrite those of earlier ones, keys preserved.
array_fill_keys(array $keys, mixed $value): mixed
array_fill_keys(["a","b"], $v) — map with those keys, each mapped to $v.
array_key_first(array $a): mixed
First key of the array (null when empty).
array_key_last(array $a): mixed
Last key of the array (null when empty).
usort(array $a, closure $cmp): bool
usort($arr, $cmp) — sorts by value in place using a comparator closure returning -1/0/1.
uasort(array $a, closure $cmp): bool
usort with key association preserved (for maps).
uksort(array $a, closure $cmp): bool
Sorts the map in place by key using a comparator closure.
array_walk(array $a, closure $fn): bool
array_walk($arr, $fn) — calls $fn($value, $key) for every element; the closure may modify $value via a by-ref parameter.
array_walk_recursive(array $a, closure $fn): bool
Like array_walk() but descends into nested arrays.
array_map(closure $fn, array $a[, array ...$args]): mixed
array_map($fn, $arr[, $arr2, …]) — applies the closure to every element and returns the results. With several arrays the closure gets one argument per array.
array_filter(array $a[, closure $fn]): mixed
array_filter($arr[, $fn]) — keeps elements where $fn returns true; without $fn keeps all truthy elements. Keys are preserved.
array_reduce(array $a, closure $fn[, mixed $initial]): mixed
array_reduce($arr, $fn[, $initial]) — folds the array left-to-right: $fn($carry, $item).
array_flip(array $a): mixed
Swaps keys and values: ["a" => 1] becomes [1 => "a"].
array_fill(int $start, int $num, mixed $value): mixed
array_fill($start, $num, $value) — $num copies of $value starting at index $start.
array_combine(array $keys, array $values): mixed
array_combine($keys, $values) — builds a map using one array as keys and the other as values.
array_diff(array ...$args): mixed
array_diff($a, $b, …) — values of $a that do not appear in any other array.
array_intersect(array ...$args): mixed
array_intersect($a, $b, …) — values of $a that appear in all other arrays.
array_push(array $a, mixed ...$args): int
Appends one or more values to the end of the array; returns the new count. $arr[] = v is preferred.
array_pop(array $a): mixed
Removes and returns the last element of the array (null when empty).
array_shift(array $a): mixed
Removes and returns the first element, re-indexing the rest (null when empty).
array_unshift(array $a, mixed ...$args): int
Prepends one or more values to the front of the array; returns the new count.
array_splice(array $a, int $offset[, int $length, array $replacement]): mixed
array_splice($arr, $offset[, $length[, $replacement]]) — removes a section and optionally replaces it; returns the removed elements.
shuffle(array $a): bool
Randomly reorders the array in place (not cryptographically secure).
sort(array $a): bool
Sorts the array in place by value, ascending, re-indexing 0..n.
rsort(array $a): bool
Sorts the array in place by value, descending, re-indexing.
ksort(array $a): bool
Sorts the map in place by key, ascending, keeping key/value association.
krsort(array $a): bool
Sorts the map in place by key, descending.
asort(array $a): bool
Sorts the map in place by value, ascending, keeping key/value association.
end(array $a): mixed
Advances the internal pointer to the last element and returns its value.
reset(array $a): mixed
Rewinds the internal pointer to the first element and returns its value.
is_array(mixed $v): bool
true when the value is an array or map.
ui_range(...$args): int
ui_range($h, $lo, $hi) — minimum and maximum of a slider or progress control.
ui_count(...$args): int
ui_count($h) — number of items in a list or combo control.
ui_browser_key(...$args): int
ui_browser_key($b, $mod, $vk, $cmd, $callback) — binds a keyboard shortcut inside the browser.
thr_current(): int
Id of the calling thread.
thr_cpu_count(): int
Number of hardware threads — use it to size a worker pool.
thr_parallel_map(...$args): mixed
thr_parallel_map($closure, $items[, $workers]) — maps the closure over the array on several threads and returns the results in order.
chan_send(...$args): bool
chan_send($ch, $value) — blocks until the value is taken; throws when the channel is closed.
chan_try_send(...$args): bool
Like chan_send() but returns false instead of blocking.
bt_count_key(...$args): int
Counts entries with the given key in an index cursor.
bt_count_range(...$args): int
Counts entries per key in [lo,hi] with one index walk; writes the counts into a typed int array and returns 0 on success.
bt_multi_keys(...$args): int
Fills a typed int array with the rowids of a batch result and returns their count.
bt_next(...$args): int
Moves a cursor forward (1 = found, 0 = end).
bt_prev(...$args): int
Moves a cursor backward (1 = found, 0 = start).
sb_prepend(...$args): bool
Inserts a string before the current contents.
scope_end(): bool unsafe
Unsafe: ends a request scope and invalidates every value allocated inside it. Compatibility builtin: no-op in this core; counters only (phase 2 removes the calls).
sqlite_column_int(...$args): int
Integer value of a column in the current row.
sqlite_column_text(...$args): string
Text value of a column in the current row.
sqlite_extended_errcode(...$args): int
Extended SQLite error code of the connection.
sqlite_reset(...$args): int
Resets a statement so it can be stepped again; bindings are kept.

Regex (5 functions)

PCRE-style pattern matching on the built-in backtracking engine. Patterns use /.../ delimiters with trailing flags i, s, m; \d \w \s classes, captures and alternation are supported. A bad pattern returns false, it does not throw.

preg_match(string $pattern, string $subject[, array $matches]): mixed
preg_match($pattern, $subject[, &$matches]) — tries the pattern once on $subject. Returns 1 and fills $matches (index 0 = full match, 1..n = capture groups) on success, false on no match or bad pattern. Patterns use /.../ delimiters with flags i (case-insensitive), s (dotall), m (multiline).
preg_match_all(string $pattern, string $subject[, array $matches]): mixed
preg_match_all($pattern, $subject[, &$matches]) — finds every non-overlapping match. Returns the number of matches and fills $matches with one array per match (each like preg_match's $matches).
preg_replace(string $pattern, string $replacement, string $subject): mixed
preg_replace($pattern, $replacement, $subject) — replaces every match. $replacement may reference captures as $1, $2, … Returns the modified string.
preg_split(string $pattern, string $subject): mixed
preg_split($pattern, $subject) — splits $subject at every match of the pattern and returns the pieces as an array.
preg_grep(string $pattern, array $arr): mixed
preg_grep($pattern, $array) — returns the elements of $array that match the pattern (keys are re-indexed 0..n).

Time (10 functions)

Unix timestamps are the base (int seconds since 1970). date() formats them, strtotime()/mktime() build them, hrtime() measures with nanosecond precision for benchmarks. exit/die live here because they end the program like a clock would end a party.

mktime(int $hour, int $minute, int $second, int $month, int $day, int $year): int
mktime($h, $m, $s, $month, $day, $year) — builds a Unix timestamp from local date/time parts.
checkdate(int $month, int $day, int $year): bool
checkdate($month, $day, $year) — true when the date is a valid calendar date (knows leap years).
microtime(): float
Current time as float seconds with microsecond precision (e.g. 1691234567.1234).
hrtime(): int
High-resolution monotonic counter in nanoseconds — use for benchmarking, immune to clock changes.
date(string $format[, int $timestamp]): string
date($format[, $timestamp]) — formats the timestamp (default: now) according to $format. Supported: Y y m n d j H G i s a A D l M N W t L U.
time(): int
Current Unix timestamp — seconds since 1970-01-01 UTC.
usleep(int $microseconds): void
Pauses the program for the given number of microseconds.
sleep(int $seconds): int
Pauses the program for the given number of seconds.
exit([int $code]): void
Terminates the program immediately with the given exit code (default 0). Alias: die().
die([int $code]): void
Alias of exit().

Hash & encode (8 functions)

Checksums (crc32, md5, sha1 — legacy), real hashes (sha256), keyed signatures (hash_hmac) and password storage (password_hash/verify, PBKDF2-SHA256). Rule of thumb: password_hash for logins, sha256 for everything else, hash_equals for comparing secrets.

sha256(string $s): string
SHA-256 hash as 64-char hex. The general-purpose hash of this runtime.
hash_hmac(string $algo, string $data, string $key): mixed
hash_hmac("sha256", $data, $key) — keyed HMAC-SHA256 for signing messages.
hash_equals(string $known, string $user): bool
Timing-safe string comparison for verifying hashes/signatures — always use it for secrets instead of ===.
md5(string $s): string
MD5 hash as 32-char hex. Fast but broken for security — checksums only.
sha1(string $s): string
SHA-1 hash as 40-char hex. Also legacy — prefer sha256().
crc32(string $s): int
CRC-32 checksum of the data as an integer — detects accidental corruption, not tampering.
base64_encode(string $s): string
Encodes bytes as Base64 text (with = padding) — for safe transport in JSON, URLs-after-urlencode, etc.
base64_decode(string $s): string
Decodes Base64 back to raw bytes. Invalid characters are skipped.

Types & vars (25 functions)

Introspection and conversion. var_dump() is your debugging friend. The compiler also checks types statically — these functions matter at runtime when values arrive untyped (JSON, user input, mixed params).

unset(mixed $var): void
unset($arr["k"]) removes the key from the array; unset($var) is not needed for locals.
json_encode(mixed $v[, int $flags]): string
Encodes a value as JSON. Flags: JSON_PRETTY_PRINT (indented), JSON_UNESCAPED_SLASHES (keep /), JSON_NUMERIC_CHECK, JSON_FORCE_OBJECT. Combine with |.
json_encode_pretty(mixed $v): string
json_encode() with JSON_PRETTY_PRINT pre-applied — convenience wrapper.
json_decode(string $s[, bool $assoc]): mixed
Decodes a JSON string into arrays/maps/scalars. Optional second argument ($assoc) is accepted for PHP compatibility and ignored.
isset(mixed $var): bool
isset($arr["k"]) — true when the key exists and the value is not null.
is_int(mixed $v): bool
true when the value is an integer. Aliases: is_integer().
is_integer(mixed $v): bool
Alias of is_int().
is_float(mixed $v): bool
true when the value is a float.
is_bool(mixed $v): bool
true when the value is true or false.
is_null(mixed $v): bool
true when the value is null.
is_numeric(mixed $v): bool
true when the value is a number or a numeric string like "42" or "3.5".
intval(mixed $v): int
Converts to int, truncating floats and parsing the leading integer of strings (0 when not numeric).
floatval(mixed $v): float
Converts to float. Alias: doubleval().
boolval(mixed $v): bool
Converts to bool using PHP truthiness (0, "", "0", [], null are false).
gettype(mixed $v): string
Type name as a string: "int", "float", "string", "bool", "array", "null", …
var_dump(mixed $v): void
Prints type and value of one or more expressions, recursively for arrays — the main debugging tool.
print_r(mixed $v): string
Human-readable dump of a value (arrays indented). Returns the text instead of printing it.
var_export(mixed $v): string
Returns a string of PHP code that would recreate the value.
serialize(mixed $v): string
Serializes the value into a storable string (HolyPHP's own format — do not exchange with PHP's).
unserialize(string $s): mixed
Restores a value serialized by serialize(). Never unserialize untrusted input.
is_dir(string $path): bool
true when the path is an existing directory.
is_file(string $path): bool
true when the path is an existing regular file.
is_readable(string $path): bool
true when the file exists and can be read.
is_writable(string $path): bool
true when the file exists and can be written.
json_num_field(string $j, string $key): int
Reads one integer field of a flat JSON object without a full parse.

System & I/O (52 functions)

Files (whole-file helpers plus fopen-style streaming), directories, process environment and external commands. The stream_* family is the raw TCP layer the registry server and WebSocket library are built on.

fgetc(resource $handle): mixed
Reads a single character from a file handle.
readline(string $prompt): string
Prints the prompt and reads one line from stdin (for interactive scripts).
file_get_contents(string $path): mixed
Reads an entire file into a string. Throws when the file cannot be opened.
file_put_contents(string $path, string $data[, int $flags]): mixed
file_put_contents($path, $data[, $flags]) — writes the string/binary data to the file. Flag PHP_FILE_APPEND appends instead of truncating.
file_exists(string $path): bool
true when a file or directory exists at the path.
filesize(string $path): int
Size of the file in bytes.
mkdir(string $path[, bool $recursive]): bool
mkdir($path[, $recursive]) — creates a directory; with $recursive true it creates parents too.
rmdir(string $path): bool
Removes an (empty) directory.
rename(string $from, string $to): bool
Renames or moves a file (also across directories).
copy(string $from, string $to): mixed
Copies the file's contents to a new path.
fgets(resource $handle): mixed
Reads one line (up to and including the newline) from a file handle. Returns false at end of file.
fwrite(resource $handle, string $data): int
fwrite($handle, $data) — writes the data; returns the number of bytes written.
fopen(string $path, string $mode): mixed
fopen($path, $mode) — opens a file handle for streaming ("r" read, "w" truncate+write, "a" append, "rb"/"wb" binary).
fclose(resource $handle): bool
Closes a file handle opened by fopen(). Always do this for written files.
scandir(string $path): mixed
Lists the entries of a directory as an array (including "." and "..").
dirname(string $path): string
Directory part of a path: dirname("a/b/c.txt") → "a/b".
basename(string $path[, string $suffix]): string
File name part of a path: basename("a/b/c.txt") → "c.txt". Optional second argument strips a suffix.
pathinfo(string $path): mixed
pathinfo($path) — map with dirname, basename, extension and filename.
realpath(string $path): mixed
Resolves relative parts and returns the canonical absolute path (false when it does not exist).
touch(string $path): bool
Creates the file if missing, otherwise updates its modification time.
sys_get_temp_dir(): string
Path of the system's temporary directory.
fread(resource $handle, int $max): string
fread($handle, $max) — reads up to $max bytes from a file handle.
feof(resource $handle): bool
true when the file handle has reached end of file.
getcwd(): string
Current working directory of the process.
bindec(string $s): int
Parses a binary string ("1010") into an integer.
octdec(string $s): int
Parses an octal string ("777") into an integer.
hexdec(string $s): int
Parses a hexadecimal string ("ff") into an integer.
getenv(string $name): string
Value of the environment variable (empty string when unset).
putenv(string $assignment): bool
putenv("NAME=value") — sets an environment variable for this process.
php_uname(): string
Operating system description string, e.g. "Windows NT …".
phpversion(): string
Version of the HolyPHP runtime (duplicate entry kept for lookup stability).
php_sapi_name(): string
Interface name — "cli" for command line builds.
memory_get_usage(): int
Bytes currently allocated by the runtime's heap.
memory_get_peak_usage(): int
Largest amount of memory the process has used so far.
gc_collect_cycles(): int
Forces a garbage-collection pass; returns the number of freed objects.
sys_getloadavg(): mixed
System load average as an array (platform-dependent, mostly informational).
php_logo_guid(): string
Returns the logo identifier (kept for PHP-compat novelty; safe to ignore).
php_sapi(): string
Alias of php_sapi_name().
shell_exec(string $command): mixed
Runs an external command and returns its complete stdout as a string.
exec(string $command): mixed
Runs an external command, discards its output, returns the last line (Windows: cmd /c).
passthru(string $s): void
Runs an external command and forwards its raw binary output to stdout.
proc_open(...$args): mixed
Starts an external process with separate pipes — advanced process control.
proc_get_status(...$args): mixed
proc_get_status($h) — status array of a process started with proc_start() (still running, exit code, …).
proc_start(...$args): int
proc_start($cmd[, $cwd]) — starts a process without blocking; returns its handle, or 0 when it could not start.
proc_read(...$args): string
proc_read($h[, $max]) — what the process has written to stdout so far; empty string when nothing is pending.
proc_read_err(...$args): string
proc_read_err($h[, $max]) — the same for stderr.
proc_write(...$args): int
proc_write($h, $data) — writes to the process's stdin; returns the number of bytes written.
proc_alive(...$args): bool
proc_alive($h) — true while the process is still running.
proc_exit(...$args): int
proc_exit($h) — exit code once it finished, -1 while it is still running.
proc_close(...$args): int
proc_close($h) — releases the handle slot of a process.
proc_kill(...$args): int
proc_kill($h) — terminates the process and its children.

HTTP & MySQL (11 functions)

A small HTTP client (http:// only — no TLS in the runtime) and a native MySQL/MariaDB wire-protocol client. http_get/post return ["status", "body", "contentType"] maps or false on failure; mysql_query returns rows as maps.

http_post(string $url, string $body[, array $headers]): mixed
http_post($url, $body[, $headers]) — HTTP POST with the body string and optional header lines (e.g. "Content-Type: application/json"). Same return shape as http_get().
http_build_query(map $data): string
Turns a map into an urlencoded query string: ["a" => "x y"] → "a=x+y".
mysql_connect(string $host[, int $port, string $user, string $pass, string $db]): mixed
mysql_connect($host[, $port[, $user[, $pass[, $db]]]]) — opens a MySQL/MariaDB connection (native wire protocol, TCP). Returns a connection handle or false.
mysql_query(resource $conn, string $sql): mixed
mysql_query($conn, $sql) — runs a SELECT/SHOW and returns the rows as an array of maps (column name => value), false on error. For INSERT/UPDATE/DELETE use mysql_exec().
mysql_exec(resource $conn, string $sql): mixed
mysql_exec($conn, $sql) — runs a statement and returns the number of affected rows, false on error.
mysql_insert_id(resource $conn): int
AUTO_INCREMENT value generated by the last INSERT on this connection.
mysql_close(resource $conn): bool
Closes the MySQL connection.
mysql_escape(string $s): string
Escapes a string for safe embedding in SQL text (see the crypto group entry).
http_get(string $url): mixed
http_get($url) — performs an HTTP GET (http:// only, no TLS) and returns ["status" => 200, "body" => …, "contentType" => …], or false on failure.
http_request(string $url, string $method[, string $body, array $headers]): mixed
http_request($url, $method, $body, $headers) — generic HTTP request for custom verbs (PUT, DELETE, …).
http_request_bounds(...$args): int
Scans an HTTP request head once and packs the request-line and header end offsets into one integer (0 = not complete, -1/-2 = error/overflow).

SQLite

SQLite is built into the compiler: a pinned, statically linked SQLite 3.46.1, the generic sqlite_* statement API, WAL checkpoint helpers and bt_* cursors that read SQLite's B-trees directly. No package to install, no import, no system libsqlite3 — programs that never call these builtins do not carry SQLite at all.

built in SQLite 3.46.1 WAL B-tree cursors raw handles: unsafe

At a glance

CallWhat it does
sqlite_open($path)open an existing database file; returns a handle, 0 on failure
sqlite_open_vfs($path, $vfs)same through a named VFS (for example "unix-excl")
sqlite_exec($db, $sql)run one or more statements; true on success
sqlite_prepare($db, $sql) / sqlite_step($st)compile one statement and advance it row by row (100 row, 101 done)
sqlite_bind_int / sqlite_bind_textbind a value to a 1-based ? parameter
sqlite_column_int / sqlite_column_textread a 0-based column of the current row
sqlite_reset / sqlite_clear_bindingsreuse a statement without recompiling it
sqlite_changes / sqlite_last_insert_rowidrows changed by the last write / its rowid
sqlite_errmsg / sqlite_is_lock_errorlast error text / whether it is worth retrying
sqlite_status($db)JSON with cache hits, statement time and busy counters
bt_open($db, $name, $is_index)cursor on a table or index; the low-level read path

First database

sqlite_open() opens an existing file; it deliberately does not create one, so a typo in the path cannot silently produce an empty database. touch() creates the file, then SQL does the rest.

Handles are raw pointers. A database or statement handle is SQLite's own pointer widened to an integer, and bt_* hands out payload addresses. The compiler therefore requires these calls inside unsafe { }: sqlite_open, sqlite_open_vfs, sqlite_prepare, bt_open, bt_root, bt_payload_ptr, bt_payload_pin, bt_multi_seek, bt_tail, bt_read, bt_col_off and bt_col_len. Nothing checks the integer for you; a stale handle is a dangling pointer.

The B-tree path

bt_* is what the bundled challenge server uses for its hottest reads: skip SQLite's virtual machine, seek the table B-tree by rowid or the index B-tree by key, decode the record bytes in place. It is a driver primitive, not a second SQL engine — the caller owns every buffer, page pin and cursor lifetime.

$db = sqlite_open($path);
$users = bt_open($db, "users", 0);          // table cursor
$by_name = bt_open($db, "users_name_idx", 1); // index cursor

// table: move to rowid 7 and decode the record at the cursor
if (bt_seek($users, 7) == 1) {
    $rowid = bt_rowid($users);
    $cols  = bt_cols($users);               // decode this record once
    $off   = bt_col_off(1);                 // second column, byte offset
    $len   = bt_col_len(1);
    $size  = bt_payload_size($users);       // bytes available on this page
}

// index: how many entries start with key 3, and a histogram for 1..20
$likes = bt_count_key($by_name, 3);
$hist  = iarr_new(20);
bt_count_range($by_name, 1, 20, $hist);

bt_close($users);
bt_close($by_name);
sqlite_close($db);
CallReturns
bt_first / bt_last1 on a row, 0 empty, -1 error
bt_next / bt_prev1 moved, 0 at the end
bt_seek($c, $rowid)1 found, 0 not found
bt_rowid / bt_payload_sizerowid or local payload length of the current row
bt_cols, bt_col_off, bt_col_len, bt_col_intdecode the current record; call bt_cols first, in its own statement
bt_read($c, $arr, $cols)serial type, offset, length and integer value per column, in one call
bt_count_key / bt_count_rangeindex entries with one key / per-key counts for a range
bt_multi_seek / bt_taila batch result handle; read it with bt_multi_keys, bt_multi_payloads, then bt_multi_release
bt_payload_pin / bt_page_releasekeep one payload page valid while another cursor moves

HolyPHP evaluates call arguments right-to-left, so bt_cols() and the column accessors must be separate statements — the same rule the challenge server follows.

WAL checkpoints

A write-heavy program with its own event loop can move SQLite's passive checkpointing to a worker thread, so a large WAL never stalls request handling. The worker uses a second connection to the same file.

$db = sqlite_open($path);
sqlite_exec($db, "PRAGMA journal_mode = WAL");
sqlite_exec($db, "PRAGMA wal_autocheckpoint = 0");
sqlite_bg_checkpoint_start($db, $path, 4096, 4);   // frames, max hold in ms

for (;;) {
    // serve requests ...
    sqlite_bg_checkpoint_tick($db);                // once per poll cycle
    if (sqlite_bg_checkpoint_hold($db)) {
        // commits are overtaking the copy: hold writes for a moment
    }
}
// sqlite_close($db) also stops the worker

sqlite_bg_checkpoint_start refuses when SQLite was built without thread safety or a worker is already running. On Windows the worker stays off and these three calls report false; everything else works the same.

What gets linked, and which SQLite

The vendored amalgamation lives in third_party/sqlite/ (public domain; version, checksums and the compile options are documented in its README). scripts/build.sh compiles it once per platform with src/hp_btree.c appended, because the B-tree builtins use SQLite's private structures, and embeds the static archive in the compiler. At build time the compiler writes it next to the generated program and links it only for programs that call sqlite_* or bt_*.

VariableEffect
HPHP_SQLITE_LIBlink this archive instead of the embedded one (a system or debug build)
HPHP_SQLITE_VFSVFS name; the challenge uses unix-excl so the process holds the database lock itself
HPHP_SQLITE_WAL_COALESCE1: write each commit's WAL frames with one pwrite

On Linux a bt_* program needs no libsqlite3.so: the archive is static. A plain program links neither SQLite nor io_uring.

Try it

bash benchmarks/challenge/run.sh      # build + run the 42-check challenge suite
hphp run tests/positive/bt_cursor.hphp

Source: src/hphpc/runtime/hphp_sqlite.c, src/hp_btree.c, third_party/sqlite/. Per-builtin signatures: built-in functions.

Predefined constants (14 functions)

Compile-time constants, usable anywhere a value is expected (not callable).

PHP_INT_SIZE : int
8 — bytes per int on this build.
PHP_INT_MAX : int
9223372036854775807 — largest integer.
PHP_INT_MIN : int
-9223372036854775808 — smallest integer.
PHP_EOL : string
Platform line ending (\r\n on Windows).
PHP_OS : string
Operating system family ("Windows").
PHP_VERSION : string
HolyPHP runtime version.
PHP_PI / PHP_EULER / PHP_FLOAT_EPSILON : float
π, e, and the float epsilon.
PHP_ROUND_HALF_UP / _DOWN / _EVEN / _ODD : int
Mode flags for round().
PHP_FILE_APPEND : int
Flag for file_put_contents(): append instead of truncate.
PHP_FILE_IGNORE_NEW_LINES / PHP_FILE_SKIP_EMPTY_LINES / PHP_FILE_USE_INCLUDE_PATH : int
Flags for file()/file() style helpers.
JSON_PRETTY_PRINT : int
json_encode() flag: multi-line indented output.
JSON_UNESCAPED_SLASHES : int
json_encode() flag: keep / unescaped.
JSON_NUMERIC_CHECK : int
json_encode() flag: numeric strings become numbers.
JSON_FORCE_OBJECT : int
json_encode() flag: empty arrays become {}.

UI (desktop) (100 functions)

Native desktop windows (Win32) with buttons, inputs, lists, menus, timers and dialogs — no external dependencies. Build the UI, register ui_on() callbacks, then call ui_run_main() to enter the event loop. Control kinds for ui_add(): 1 window, 2 button, 3 label, 4 input, 5 checkbox, 6 list, 7 combo, 8 progress, 9 slider, 10 group, 11 tab, 12 panel, 13 menu, 14 menuitem, 15 picture.

ui_dispatch(): int
Runs one iteration of the UI event loop (for manual/embedded loops). Prefer ui_run_main().
ui_run_main(): void
Starts the UI event loop — call once after building your windows; blocks until the last window closes.
ui_quit(): void
Ends the UI event loop and closes the application.
ui_window(string $title, int $x, int $y, int $w, int $h): int
ui_window($title, $x, $y, $w, $h) — creates a window; returns its handle.
ui_show(int $handle, bool $visible): int
ui_show($handle, $visible) — shows or hides a window/control.
ui_title(int $handle, string $title): int
Sets the window title.
ui_size(int $handle, int $w, int $h): int
ui_size($handle, $w, $h) — resizes a window/control.
ui_pos(int $handle, int $x, int $y): int
ui_pos($handle, $x, $y) — moves a window/control.
ui_close(int $handle): int
Destroys a window/control handle.
ui_alive(): bool
true while the window/event loop is still running.
ui_add(int $parent, int $kind, string $text, int $x, int $y, int $w, int $h): int
ui_add($parent, $kind, $text, $x, $y, $w, $h) — adds a control to a window. $kind: 1=window 2=button 3=label 4=input 5=checkbox 6=list 7=combo 8=progress 9=slider 10=group 11=tab 12=panel 13=menu 14=menuitem 15=picture. Returns the control handle.
ui_set(int $handle, string $text): int
Sets the text of a control (label, button, input value, …).
ui_get(int $handle): string
Reads the current text/value of a control (e.g. an input field).
ui_enable(int $handle, bool $enabled): int
ui_enable($handle, $enabled) — enables/disables a control.
ui_move(int $handle, int $x, int $y): int
Moves a control inside its parent.
ui_focus(int $handle): int
Gives the keyboard focus to a control.
ui_select_all(...$args): int
ui_select_all($h) — selects the whole text of an edit control, as if Ctrl+A were pressed.
ui_items(int $handle): int
Number of items in a list/combo control.
ui_remove(int $handle, int $index): int
ui_remove($handle, $index) — removes an item from a list/combo.
ui_clear(int $handle): int
Removes all items from a list/combo (or text from an input).
ui_ctrl_show(int $handle, bool $visible): int
Shows/hides a single control.
ui_selected(int $handle): int
Index of the selected item in a list/combo (-1 when none).
ui_select(int $handle, int $index): int
ui_select($handle, $index) — selects an item programmatically.
ui_item_text(int $handle, int $index): string
Text of the item at the given index.
ui_check_get(int $handle): int
true when a checkbox is checked.
ui_check_set(int $handle, bool $checked): int
ui_check_set($handle, $checked) — sets a checkbox.
ui_progress(int $handle, int $percent): int
ui_progress($handle, $percent) — sets a progress bar (0–100).
ui_slider_get(int $handle): int
Current value of a slider.
ui_slider_set(int $handle, int $value): int
Sets a slider's value.
ui_bg(int $handle, int $color): int
ui_bg($handle, $color) — background color (RGB int, e.g. 0xFF0000 for red).
ui_fg(int $handle, int $color): int
Foreground (text) color as RGB int.
ui_font(int $handle, int $size[, bool $bold, bool $italic, string $family]): int
ui_font($handle, $size[, $bold[, $italic[, $family]]]) — sets a control's font.
ui_menu(int $win, string $title): int
Creates a menu bar / menu for a window.
ui_menu_item(int $menu, string $title): int
Appends an item to a menu; returns its handle (for ui_on callbacks).
ui_menu_sep(int $menu): int
Appends a separator line to a menu.
ui_menu_check(int $handle, bool $checked): int
ui_menu_check($handle, $checked) — checkable menu item state.
ui_on(int $handle, string $event, closure $callback): int
ui_on($handle, $event, $callback) — registers a closure for events: "click", "change", "select", "close", … The closure receives event-specific arguments.
ui_timer(int $ms, closure $callback): int
ui_timer($ms, $callback) — runs the closure every $ms milliseconds until ui_quit().
ui_msg(int $win, string $title, string $text[, int $type]): int
ui_msg($win, $title, $text[, $type]) — message box. $type: 0=info 1=warning 2=error 3=question.
ui_open_file(string $title): mixed
Opens the platform file-open dialog; returns the chosen path or false.
ui_save_file(string $title): mixed
Opens the platform save-file dialog; returns the chosen path or false.
ui_pick_folder(string $title): mixed
Folder-picker dialog; returns the path or false.
ui_pick_color(): mixed
Color-picker dialog; returns the RGB int or false.
ui_clip_set(string $text): int
Copies text to the system clipboard.
ui_clip_get(): string
Reads text from the system clipboard.
ui_theme(...$args): int
ui_theme($win, $bg, $surface, $elevated, $text, $muted, $accent, $onAccent, $border, $radius, $fontPt, $titlePt, $rowH, $dark) — sets the look of a window and every control in it.
ui_style(...$args): int
ui_style($h, $role) — assigns a style role to a control, i.e. how it is painted.
ui_accent(...$args): int
ui_accent($h, $rgb) — accent colour of a control, e.g. 0xFF8C00.
ui_radius(...$args): int
ui_radius($h, $px) — corner radius of a control in pixels.
ui_repaint(...$args): int
ui_repaint($h) — schedules a redraw of the window/control.
ui_input_margin(...$args): int
ui_input_margin($h, $left, $right) — insets the text of an edit control (room for an icon, e.g. in an address bar).
ui_raise(...$args): int
ui_raise($h) — brings a window or control to the front.
ui_svg(...$args): int
ui_svg($h, $source) — sets the SVG markup drawn by a picture control.
ui_picture(...$args): int
ui_picture($h, $path) — loads an image file into a picture control.
ui_text_px(...$args): int
ui_text_px($text, $pt, $bold) — measured width of that string in pixels.
ui_text_lines(...$args): int
ui_text_lines($text, $pt, $bold, $maxWidth) — how many lines the text wraps to at that width.
ui_enabled(...$args): bool
ui_enabled($h) — true when the control still accepts input (ui_enable() toggles it).
ui_rect(...$args): mixed
ui_rect($h) — [x, y, w, h] of a control in its parent's coordinates, or null.
ui_client_size(...$args): mixed
ui_client_size($win) — [width, height] of a window's client area.
ui_scroll(...$args): mixed
ui_scroll($win, $dy, $to) — scrolls by $dy (or to $to) and returns [offset, contentHeight, viewportHeight].
ui_progress_get(...$args): int
ui_progress_get($h) — current value of a progress bar.
ui_hwnd(...$args): int
ui_hwnd($win) — the native window handle (HWND) of a window.
ui_font_new(...$args): int
ui_font_new($family, $pt, $bold, $italic) — creates a font for canvas drawing and returns its id.
ui_font_width(...$args): int
ui_font_width($font, $text) — width of that string in the given font, in pixels.
ui_font_height(...$args): int
ui_font_height($font) — line height of the given font, in pixels.
ui_draw_clear(...$args): int
ui_draw_clear($cv, $rgb) — fills the whole canvas with one colour.
ui_draw_rect(...$args): int
ui_draw_rect($cv, …) — draws a rectangle on the canvas.
ui_draw_round(...$args): int
ui_draw_round($cv, …) — draws a rectangle with rounded corners on the canvas.
ui_draw_line(...$args): int
ui_draw_line($cv, …) — draws a line on the canvas.
ui_draw_text(...$args): int
ui_draw_text($cv, …) — draws text on the canvas with the current font and colour.
ui_draw_clip(...$args): int
ui_draw_clip($cv, …) — restricts further drawing to a rectangle.
ui_draw_unclip(...$args): int
ui_draw_unclip($cv) — removes the clip rectangle again.
ui_canvas_size(...$args): mixed
ui_canvas_size($cv) — [width, height] of the drawing surface in pixels.
ui_canvas_pixel(...$args): int
ui_canvas_pixel($cv, $x, $y) — RGB value of the pixel at that position.
ui_canvas_invalidate(...$args): int
ui_canvas_invalidate($cv, …) — marks a region dirty so it is repainted.
ui_canvas_flush(...$args): int
ui_canvas_flush($cv) — pushes everything drawn since the last flush to the screen.
ui_cursor(...$args): int
ui_cursor($cv, $shape) — sets the mouse cursor shown over the canvas.
ui_browser_ready(): bool
true when the embedded Chromium runtime (WebView2) is available on this machine.
ui_browser_loader(): string
HTML of the loading splash shown while a page starts; empty string when none is set.
ui_browser_new(...$args): int
ui_browser_new($parent, $dir) — creates an embedded browser inside a window; returns its handle.
ui_browser_free(...$args): int
ui_browser_free($b) — destroys a browser handle.
ui_browser_fit(...$args): int
ui_browser_fit($b, $top, $width) — resizes the browser area inside its window.
ui_browser_go(...$args): int
ui_browser_go($b, $url) — navigates the browser to a URL.
ui_browser_back(...$args): int
Goes back in the session history.
ui_browser_forward(...$args): int
Goes forward in the session history.
ui_browser_reload(...$args): int
Reloads the current page.
ui_browser_stop(...$args): int
Stops loading the current page.
ui_browser_can_back(...$args): bool
true when there is a page to go back to.
ui_browser_can_forward(...$args): bool
true when there is a page to go forward to.
ui_browser_favicon(...$args): string
URL of the current page's favicon.
ui_browser_title(...$args): string
Title of the current document.
ui_browser_zoom(...$args): int
ui_browser_zoom($b, $factor) — sets the page zoom, 1.0 = 100 %.
ui_browser_zoom_get(...$args): float
Current zoom factor of the browser.
ui_browser_devtools(...$args): int
ui_browser_devtools($b, $on) — opens or closes the developer tools.
ui_browser_devtools_fit(...$args): int
Keeps the browser area sized correctly while the devtools panel is docked.
ui_browser_devtools_ready(...$args): int
true once the devtools window is up.
ui_browser_print(...$args): int
Opens the print dialog for the current page.
ui_browser_post(...$args): int
ui_browser_post($b, $url, …) — performs an HTTP POST from the browser context.
ui_browser_on(...$args): int
ui_browser_on($b, $event, $callback) — registers a closure for browser events (navigation, load, …).
ui_browser_visible(...$args): int
ui_browser_visible($b, $on) — shows or hides the embedded browser.

Unsafe / FFI (6 functions)

Escape hatches to raw memory and native shared libraries. Every one of these requires an unsafe { } block in the compiler — with intent: this is where memory bugs live.

free(pointer $ptr): void unsafe
unsafe: frees a raw pointer obtained from FFI. Wrong use corrupts memory — this is why it needs an unsafe block.
memcpy(pointer $dst, pointer $src, int $n): mixed unsafe
unsafe: copies $n bytes from one raw address to another.
memset(pointer $dst, int $byte, int $n): mixed unsafe
unsafe: fills $n bytes at an address with a byte value.
ffi_load(string $path): mixed unsafe
unsafe: ffi_load("mylib.dll") — loads a shared library for direct native calls. Returns a library handle or false.
ffi_call(resource $lib, string $symbol): mixed unsafe
unsafe: ffi_call($lib, "symbol") — resolves an exported function in a loaded library; call the result with the documented signature.
heap_dump(): string unsafe
Unsafe: returns a debug dump of the runtime heap with raw allocation addresses (allocation count, sizes).

Other (136 functions)

chop(string $s): string
Alias of rtrim(): strips trailing whitespace.
split(string $separator, string $s): mixed
Alias of explode(); an empty separator splits the string into single characters.
M_PI(): float
The constant π as a callable fallback — prefer the constant.
doubleval(mixed $v): float
Alias of floatval().
glob(string $pattern): mixed
glob($pattern) - file paths matching a shell wildcard pattern ("*.hphp", "src/*/*.c") as an array.
decbin(int $n): string
Integer to binary string: decbin(10) -> "1010".
decoct(int $n): string
Integer to octal string: decoct(8) -> "10".
dechex(int $n): string
Integer to hexadecimal string: dechex(255) -> "ff".
RESET(...$args): int
Colour constant: the terminal's default colour. Pass it as the second argument of print()/println()/input() to end a coloured line.
BLACK(...$args): int
Colour constant: black — optional second argument of print()/println()/input().
RED(...$args): int
Colour constant: red — optional second argument of print()/println()/input().
GREEN(...$args): int
Colour constant: green — optional second argument of print()/println()/input().
YELLOW(...$args): int
Colour constant: yellow — optional second argument of print()/println()/input().
BLUE(...$args): int
Colour constant: blue — optional second argument of print()/println()/input().
MAGENTA(...$args): int
Colour constant: magenta — optional second argument of print()/println()/input().
CYAN(...$args): int
Colour constant: cyan — optional second argument of print()/println()/input().
WHITE(...$args): int
Colour constant: white — optional second argument of print()/println()/input().
BRIGHT_BLACK(...$args): int
Colour constant: bright black (dark grey) — optional second argument of print()/println()/input().
BRIGHT_RED(...$args): int
Colour constant: bright red — optional second argument of print()/println()/input().
BRIGHT_GREEN(...$args): int
Colour constant: bright green — optional second argument of print()/println()/input().
BRIGHT_YELLOW(...$args): int
Colour constant: bright yellow — optional second argument of print()/println()/input().
BRIGHT_BLUE(...$args): int
Colour constant: bright blue — optional second argument of print()/println()/input().
BRIGHT_MAGENTA(...$args): int
Colour constant: bright magenta — optional second argument of print()/println()/input().
BRIGHT_CYAN(...$args): int
Colour constant: bright cyan — optional second argument of print()/println()/input().
BRIGHT_WHITE(...$args): int
Colour constant: bright white — optional second argument of print()/println()/input().
print(mixed $value[, int $colour]): void
print($value[, $colour]) — writes to stdout without a newline. The optional second argument is one of the colour constants below.
println(mixed $value[, int $colour]): void
println($value[, $colour]) — like print() but ends the line. A colour wraps only this one line and is reset afterwards.
input(string $prompt[, int $colour]): string
input($prompt[, $colour]) — prints the prompt (optionally coloured), reads one line from stdin and returns it without the newline.
thr_spawn(...$args): mixed
thr_spawn($closure[, $args]) — runs the closure on a new thread; returns the thread id or false.
thr_id(): int
OS-level id of the calling thread.
thr_sleep_ms(int $n): void
thr_sleep_ms($ms) — sleeps the current thread.
chan_new(int $n): int
chan_new($capacity) — creates a channel; capacity 0 means unbuffered (rendezvous, Go style).
chan_recv(...$args): mixed
chan_recv($ch) — blocks for the next value; false once the channel is closed and drained.
chan_try_recv(...$args): mixed
Like chan_recv() but returns false instead of blocking.
chan_close(...$args): bool
Closes the channel: further sends fail, receives drain what is left and then return false.
mutex_new(): int
Creates a mutex and returns its id.
mutex_lock(...$args): bool
Locks the mutex, blocking until it is free.
mutex_trylock(...$args): bool
Locks the mutex only if it is free right now; false otherwise.
mutex_unlock(...$args): bool
Unlocks the mutex.
mutex_free(...$args): bool
Releases the mutex id for reuse.
barrier_new(int $n): int
barrier_new($n) — creates a barrier that releases once n threads have arrived.
barrier_wait(...$args): int
Waits at the barrier; returns the arrival index of the last thread to arrive.
atomic_new(...$args): int
atomic_new([$init]) — creates an atomic int (default 0) and returns its id.
atomic_get(...$args): int
Reads an atomic value.
atomic_set(...$args): bool
atomic_set($a, $value) — stores a value atomically.
atomic_add(...$args): int
atomic_add($a, $delta) — adds and returns the previous value.
atomic_cas(...$args): bool
atomic_cas($a, $expect, $set) — compare-and-set; true when the value was $expect and became $set.
malloc(int $n): mixed unsafe
unsafe: allocates n bytes of raw memory; returns a pointer for memcpy/memset/ffi. Must be freed with free().
accept_emfile(...$args): bool
Whether the last accept failed because the process ran out of descriptors.
arr_clear(array $a): bool
Empties an array in place, keeping its allocated key/value storage.
arr_free(array $a): bool unsafe
Unsafe: frees an array and its element storage early (the values themselves are not released). A second call is a double free.
bt_close(...$args): bool
Closes a B-tree cursor.
bt_col_int(...$args): int
Integer value of a column inside the current record.
bt_col_int_at(...$args): int
Integer value of a column of another cursor's current record.
bt_col_len(...$args): int unsafe
Unsafe: byte length of a column inside the current record, taken from the cached decoder without re-checking the record.
bt_col_off(...$args): int unsafe
Unsafe: byte offset of a column inside the current record, taken from the cached decoder without re-checking the record.
bt_cols(...$args): int
Number of columns in the current record.
bt_first(...$args): int
Moves a cursor to the first entry (1 = found).
bt_last(...$args): int
Moves a cursor to the last entry (1 = found).
bt_multi_payloads(...$args): bool unsafe
Unsafe: fills a typed int array with found/pointer/size triples; the pointers are raw SQLite page addresses valid only until bt_multi_release.
bt_multi_release(...$args): bool unsafe
Unsafe: releases a batch result and the raw pages it pins. Using the result afterwards is a use-after-free.
bt_multi_seek(...$args): int unsafe
Unsafe: resolves many rowids with one batch of cursor positions and returns a raw result pointer that must go through bt_multi_release.
bt_open(...$args): int unsafe
Opens a cursor on a table or index and returns a handle. Unsafe: raw B-tree access.
bt_page_release(...$args): bool unsafe
Unsafe: releases a raw page token returned by bt_payload_pin. Releasing it twice corrupts the page cache.
bt_payload_pin(...$args): int unsafe
Unsafe: pins the current payload page and returns a raw page pointer that only bt_page_release may consume.
bt_payload_ptr(...$args): int unsafe
Unsafely returns the address of the current record's payload bytes.
bt_payload_size(...$args): int
Byte length of the current record's payload.
bt_read(...$args): int unsafe
Unsafe: decodes several columns of the current record into a typed int array (offsets, lengths and integers) and returns the column count; it trusts the cached record layout.
bt_root(...$args): int unsafe
Root page number of a table or index (0 when it cannot be resolved). Unsafe: raw B-tree access.
bt_rowid(...$args): int
Rowid at the current cursor position.
bt_seek(...$args): int
Seeks a table cursor to a rowid (1 = found).
bt_tail(...$args): int unsafe
Unsafe: reads the last n entries of a table into a raw batch result pointer that must go through bt_multi_release.
epoll_add(...$args): int
Adds a socket to the readiness set (io_uring poll or epoll, whichever is active).
epoll_del(...$args): int
Removes a socket from the readiness set.
epoll_mod(...$args): int
Changes the interest mask of a socket: 1 = readable, 2 = writable.
epoll_wait2(...$args): int
Waits for readiness and fills the two arrays with readable and writable handles.
epoll_wait_iarr2(...$args): bool unsafe
Unsafe: typed-array variant of epoll_wait2; writes through a raw typed int array without boxing or lifetime checks.
epoll_wait_into(...$args): int
Waits for readability and appends ready handles to an array.
iarr_data_ptr(int $h): int unsafe
Unsafely returns the address of the array's first element for pointer-style access.
iarr_get(int $h, int $i): int
Reads an integer from a typed int array (0 when the handle or index is invalid).
iarr_get_fast(int $h, int $i): int unsafe
Unsafely reads an integer without a bounds check (caller guarantees the index).
iarr_len(int $h): int
Number of elements in a typed int array.
iarr_new(int $n): int
Creates a zero-initialised typed int64 array of the given length and returns its handle.
iarr_new_uninit(int $n): int unsafe
Unsafe: creates a typed int64 array with uninitialised storage (fill it before reading; reading first is undefined).
iarr_release(int $h): bool unsafe
Unsafe: releases a typed int array back to the runtime pool; using the handle afterwards, or releasing it twice, is a use-after-free.
iarr_set(int $h, int $i, int $v): bool
Stores an integer in a typed int array.
iarr_set_fast(int $h, int $i, int $v): bool unsafe
Unsafely stores an integer without a bounds check (caller guarantees the index).
int_digits(int $n): int
Decimal digit count of an integer (for Content-Length and similar prefixes).
jwt_verifier_new(...$args): string
Precomputes the key state for repeated JWT verification.
jwt_verify(...$args): string
Verifies an HS256 JWT (signature, alg, exp) and returns the decoded payload, or an empty string.
jwt_verify_prepared(...$args): string
Verifies a JWT with a prepared verifier.
live_allocs(...$args): mixed
Number of live blocks tracked by the runtime allocator (0 when the core has no counter).
live_bytes(...$args): mixed
Bytes currently allocated by the runtime (0 when the core has no counter).
nofile_limit(...$args): int
Current RLIMIT_NOFILE (0 when unknown).
object_free(...$args): bool unsafe
Unsafe: frees the object struct itself, not the values it references; a second call is a double free.
runtime_diag_write(...$args): bool
Writes one diagnostic line to stderr when HPHP_DIAG=1.
runtime_stats(...$args): string
JSON snapshot of the runtime counters (requests, io_uring enters, allocations).
sb_bytes(int $h, int $p, int $n): bool unsafe
Unsafely appends len bytes read from a raw address.
sb_data_ptr(int $h): int unsafe
Unsafely returns the address of the builder contents (valid until the next append).
sb_discard(int $h): bool unsafe
Unsafe: releases a builder without taking its contents. Using the handle afterwards is a use-after-free.
sb_int(int $h, int $n): bool
Appends an integer in decimal.
sb_json(...$args): int
Appends JSON string escaping for len bytes at a raw address (the value must already be UTF-8 text).
sb_len(int $h): int
Number of bytes currently in a builder.
sb_new(): int
Creates a string builder and returns an integer handle. Use sb_take or sb_discard to release it.
sb_put(int $h, string $s): bool
Appends a string to a builder.
sb_reserve(int $h, int $n): bool
Reserves capacity in a builder so a large response does not reallocate repeatedly.
scalar_binop(...$args): mixed
Runtime support builtin ported with the io_uring/SQLite modules.
scope_begin(): bool
Starts a request scope. Compatibility builtin: this core has no request arena yet, so it is a no-op (phase 2 removes the calls).
sqlite_bg_checkpoint_active(...$args): mixed
Whether the background checkpoint worker is currently running.
sqlite_bg_checkpoint_hold(...$args): mixed
Lets the event loop ask the checkpoint worker to hold off briefly so the WAL can restart.
sqlite_bg_checkpoint_start(...$args): mixed
Starts the optional background WAL checkpoint worker for a database.
sqlite_bg_checkpoint_tick(...$args): mixed
One cheap event-loop tick for the checkpoint worker; call it once per poll cycle.
sqlite_bind_int(...$args): bool
Binds an integer to a 1-based statement parameter.
sqlite_bind_text(...$args): bool
Binds a string to a 1-based statement parameter.
sqlite_busy_timeout(...$args): bool
Milliseconds SQLite waits for a lock before returning SQLITE_BUSY.
sqlite_changes(...$args): int
Rows changed by the most recent write statement.
sqlite_clear_bindings(...$args): bool
Clears all bound parameters of a statement.
sqlite_close(...$args): mixed
Closes a SQLite database handle.
sqlite_errmsg(...$args): mixed
Last error message of the connection.
sqlite_exec(...$args): bool
Runs one or more SQL statements; true when SQLite reports SQLITE_OK.
sqlite_finalize(...$args): bool
Finalises a prepared statement.
sqlite_is_lock_error(...$args): bool
Whether the last error was a busy/locked condition worth retrying.
sqlite_last_insert_rowid(...$args): int
Rowid of the most recent successful insert.
sqlite_open(...$args): int unsafe
Opens a SQLite database file and returns a handle (0 on failure). Unsafe: the handle is a raw library pointer.
sqlite_open_vfs(...$args): int unsafe
Unsafe: opens a SQLite database through a named VFS and returns a raw library handle (0 on failure).
sqlite_prepare(...$args): int unsafe
Compiles one SQL statement and returns a statement handle (0 on error). Unsafe: raw pointer.
sqlite_status(...$args): string
Returns a compact JSON string with the connection's SQLite status counters.
sqlite_step(...$args): int
Advances a statement: 100 = row, 101 = done, anything else is an error.
uring_active(...$args): bool
Whether the io_uring backend is in use.
uring_direct(...$args): bool
Whether ring-owned direct descriptors are in use (they need no process fd).
uring_direct_slots(...$args): int
Number of registered direct-descriptor slots (0 when direct mode is off).
sb_take(int $h): string unsafe
Unsafe: returns the builder contents as a string and releases the builder; a second call is a use-after-free.
u8_at(int $p, int $off): int unsafe
Unsafely reads one byte at address+offset.
u8_set(int $p, int $off, int $v): int unsafe
Unsafely writes one byte at address+offset.
i64_at(int $p, int $off): int unsafe
Unsafely reads a 64-bit integer at address+8*offset.
i64_set(int $p, int $off, int $v): int unsafe
Unsafely writes a 64-bit integer at address+8*offset.

Command line

One binary does everything: check, run, build. The runtime and the whole standard library are embedded inside hphp.exe — nothing else to install.

Commands

CommandWhat it does
hphp check file.hphpType + borrow check only. Fastest feedback loop; prints OK (types and borrows check) or precise diagnostics with line numbers.
hphp run file.hphpCompile to a temp binary and execute it. Perfect for scripts and quick iteration.
hphp build file.hphp -o app.exeProduce a standalone executable. Ships with the runtime linked in — no dependencies on the target machine.
hphp emit file.hphpPrint the generated C (for the curious and the debugger-inclined).
hphp create [name]New project folder from a template (console, web, lib, empty). Asks a few questions in a terminal; --yes and the options from hphp create --help for scripts.
hphp run / build / checkWithout a file, inside a project: use the entry from hphp.yaml. hphp build then writes build/<name>.
hphp install [pkg[@version]]In a project: install everything from hphp.yaml into .hphp/packages/ (keeping hphp.lock), or add one dependency (--dev for require-dev, a folder such as ../mylib for a local package). Outside a project: install a package for your user, as before.
hphp update [pkg]Move dependencies to the newest version their constraint allows and rewrite hphp.lock.
hphp remove pkgDrop a dependency, its folder and whatever only it needed.
hphp depsList the locked dependencies and where they came from.
hphp test [filter] [-v]Run every tests/*.hphp of the project; a test passes when it exits 0.
hphp pkg ...Package manager: init, check, pack, publish, install, remove, search, registry, list, home. See the Packages page.

Environment variables

VariableEffect
HPHP_VERBOSE=1Show the backend compile/link commands and diagnostics detail.
HPHP_KEEP_BIN=1Keep the intermediate build directory (prog.c, objects) for inspection.
HPHP_HOMEPackage home: packages/, cache/, registry_url. Defaults to a per-user folder.
HPHP_REGISTRYRegistry URL override (default: http://hphp.ch:8930 — the public community registry).
HPHP_PATHExtra import search directories, ; (Windows) or : separated — like PHP's include_path.

Typical workflow

hphp check app.hphp          # instant: types + borrows
hphp run app.hphp            # quick run
hphp build app.hphp -o app.exe   # ship it

Editor support

A VS Code extension lives in extension/hphp: syntax highlighting, completions for all 305 builtins (generated from the compiler's own table), hover signatures, and live diagnostics that run hphp check as you type.

Under the hood

The pipeline is: lexer → recursive-descent parser → semantic analysis (types, borrows, ownership) → C codegen → cc + ld. The runtime (values, strings, COW arrays, exceptions, Win32 UI, sockets) is embedded in the compiler binary and extracted at build time, compiled with your local gcc, and linked statically — which is why output exes are a few hundred KB and start instantly.

Projects & packages

HolyPHP ships with its own package manager. Packages are plain folders of .hphp files described by an hphp.json manifest, packed into a portable .hpx archive, and shared through a registry — which is itself a HolyPHP program (registry/server.hphp, ~250 lines).

Projects: hphp create

A project is a folder with an hphp.yaml. Its dependencies are installed into the project's own .hphp/packages/ folder and pinned in hphp.lock, so every project keeps its own versions and a fresh clone gets exactly the same ones with one command.

hphp create                       # asks: name, template, description, author, license, ...
hphp create shop -t web --yes     # no questions: web template, defaults

cd shop
hphp install                      # everything in hphp.yaml (keeps hphp.lock)
hphp install websocket            # add a dependency (pins "^x.y")
hphp install thread@^1.0          # ... with a version constraint
hphp install phpunit_lite --dev   # only for development (require-dev)
hphp install ../mylib             # a local package folder (path:../mylib)
hphp update                       # newest allowed versions, rewrites hphp.lock
hphp update websocket             # just one package
hphp remove websocket             # drop it (and what only it needed)
hphp deps                         # what is installed, from where
hphp run                          # runs the entry from hphp.yaml
hphp test                         # runs tests/*.hphp (a test passes when it exits 0)
hphp build                        # writes build/shop(.exe)

Templates: console (input + colored output), web (HTTP server with routes on the async library), lib (a package with tests, ready for hphp pkg publish) and empty. hphp create --help lists the options for scripts and CI (--template, --description, --author, --license, --safe, --no-git, --yes).

Layout

shop/
  hphp.yaml            name, version, entry, require, require-dev
  hphp.lock            exact versions + checksums - commit it
  src/main.hphp        the entry file
  src/routes.hphp
  tests/routes_test.hphp
  .hphp/packages/      installed dependencies - not committed (.gitignore)
  build/               hphp build output

The project file: hphp.yaml

# HolyPHP project file
name: shop
version: 0.1.0
type: project            # or: library
description: A HolyPHP web server.
entry: src/main.hphp
author: Ada
license: MIT

require:
  async: "^1.0"          # 1.x from 1.0
  websocket: "~1.2"      # 1.2.x
  mylib: "path:../mylib" # a local folder

require-dev: {}

Version constraints: "*" any, "1.2.3" exactly, "1.2" any 1.2.x, "^1.2" 1.2 up to (not including) 2.0, "~1.2" 1.2.x, ">=1.0 <2.0" a range, "^1.0 || ^2.0" either. Quote them: * and ^ mean something else in plain YAML. The file is a small YAML subset: key: value, one level of nested name: "version" lines, {} for an empty map, and # comments.

import "async"; looks in the importing file's project (.hphp/packages/async/) before the per-user package home and the libraries bundled in the compiler. Packages come from the registry; when it is unreachable or does not have them, from the libraries bundled in hphp (works offline). The registry serves the newest version of a package only, so a constraint it cannot meet fails with a clear message instead of installing something else. hphp.lock records an FNV-1a checksum of every archive; a package that changed under the same version number stops the install.

Older projects with an hphp.json keep working; when a folder has both, hphp.yaml wins. hphp pkg pack and hphp pkg publish read hphp.yaml and add a generated hphp.json to the archive, so registries and older clients understand it; .hphp/, .git/ and build/ are left out.

Official and community packages

Every package is one of three kinds; hphp deps and hphp.lock show which (trust:).

KindWhere it comes fromOn install
officialthe libraries bundled with hphpinstalled from the compiler itself, never from a registry: a registry package can not take an official name, and the registry refuses to publish one
communitya registry or a .hpx filereviewed first: you see where it is from, its author (as it claims), and what its code can do, then answer y to install
localpath:../mylibyour own code, installed without asking
$ hphp install leftpad

  ! community package: leftpad 1.2.0
    from:    registry http://hphp.ch:8930
    author:  someone   (as written in its manifest, not verified)
    files:   2 (1 HolyPHP source)
    it can:  run shell commands         leftpad.hphp:4  shell_exec("curl ... | sh");
             write or delete files      leftpad.hphp:5  unlink("/tmp/x");

    Official libraries ship with hphp and are reviewed with it. Community
    packages are written by anyone: install only what you trust. The list
    above is a hint from reading the source, not a guarantee.

  Install leftpad 1.2.0? [y/N]

The review looks for shell commands, file writes and deletes, network connections, unsafe code, native libraries (FFI), environment changes and file reads. Answering anything but y installs nothing and leaves hphp.yaml as it was. Once accepted, the package's checksum is in hphp.lock: a fresh clone runs hphp install without asking again, and a package that changed under the same version asks again. Without a terminal (CI) nothing is installed unless you pass --trust: hphp install --trust.

Quick start

hphp pkg init                     # create hphp.json skeleton in this folder
hphp pkg check                    # typecheck the package's entry file
hphp pkg pack                     # build name-version.hpx into your pkg cache
hphp pkg publish                  # pack + upload to the configured registry
hphp pkg install mathx            # download + unpack into $HPHP_HOME/packages
hphp pkg remove mathx             # uninstall (alias: uninstall)
hphp pkg list                     # show installed packages
hphp pkg search clamp             # search the registry (falls back to local)
hphp pkg registry http://localhost:8930   # point the client at a registry
hphp pkg home                     # print the package home directory

The manifest: hphp.json

{
  "name": "mathx",
  "version": "1.0.0",
  "description": "tiny math helpers",
  "entry": "mathx.hphp",
  "author": "you"
}

entry is what hphp pkg check typechecks (defaults to <name>.hphp). Packing walks the whole package folder, so every file in it ships in the archive.

Using an installed package

hphp pkg install mathx unpacks into $HPHP_HOME/packages/mathx/. The compiler's import resolution then searches:

  1. the importing file's directory (project-local files, e.g. import "mymod" → mymod.hphp)
  2. $HPHP_HOME/packages/<name>/ (installed packages)
  3. libraries embedded in the compiler (works offline)
// app.hphp — after: hphp pkg install mathx
import "mathx";

echo "clamped: " . clampi(42, 0, 10);   // 10

Run your own registry

The registry is a normal HolyPHP program using the socket builtins (stream_socket_server, stream_ready, stream_recv, stream_send). It serves a browsable index, ?q= search, package downloads under /pkg/<name>, and accepts uploads via POST /publish.

cd registry
../hphp.exe run server.hphp          # listens on http://localhost:8930
HPHP_HOME=../store ../hphp.exe run server.hphp --store /var/hphp-packages

The public community registry runs at http://hphp.ch:8930 and is the compiled-in default of the released installers — hphp pkg install thread works out of the box. You can also browse the community packages online.

Packages live as <name>.hpx + <name>.json metadata in the store directory, so a registry can be backed up, synced, or moved to another machine by copying one folder. Point clients at it from any device:

hphp pkg registry http://your-server:8930

End-to-end walkthrough

# 1. author
mkdir mathx && cd mathx && hphp pkg init
#    ... edit mathx.hphp and hphp.json ...
hphp pkg check                        # types + borrows

# 2. share (machine A)
hphp pkg publish                      # -> uploaded to the registry

# 3. consume (machine B, same registry)
hphp pkg registry http://your-server:8930
hphp pkg install mathx
hphp run app.hphp                     # import "mathx" just works

How it works under the hood

  • .hpx format — a trivial tar-like container: repeated name  size\n headers followed by raw payload, terminated by HPHX1. Human-readable, streamable, no dependencies.
  • Package home — HPHP_HOME (defaults to a per-user folder): cache/ for downloaded archives, packages/ for installed code, registry_url for the configured server.
  • Publish — the client packs, then POSTs the archive as application/octet-stream; the server validates the embedded manifest and stores it.
  • Install — the client downloads, unpacks to a temp dir, validates the manifest, then moves it into packages/<name>.

HolyIDE

HolyIDE: an editor and a workbench for HolyPHP, written in HolyPHP on top of the html library. Its package (packages/lib/ide) is the whole IDE except the window, which is why all of it is tested without one.

a program written in HolyPHP text buffer + undo syntax + completions explorer, tabs, palette runs hphp from the IDE

Two halves, one import

FileWhat it is
ide/editor.hphpthe document model: lines, caret and selection, editing keys, undo/redo, the syntax tokenizer, the completion vocabulary
ide/workbench.hphpthe chrome: explorer tree, tabs, code pane, terminal and problems panel, status bar, command palette, key table, runner — rendered to HTML and handed to an HtmlView
holyide/holyide.hphpthe window: one canvas, forwarded events, a frame timer. Not part of the library — it is the ~140-line app around it.

The editor on its own

The buffer, the caret and the editing operations have no idea a screen exists. Load a file, type into it, undo, save — no window anywhere.

import "ide";

$ed = new IdeEditor();
$ed->load("holyide/holyide.hphp");
$ed->move("docstart", false);
$ed->type_char("/");
$ed->type_char("/");
echo substr($ed->line(0), 0, 20);   // //// ==== ...
$ed->undo_step();
echo $ed->status();         // undo/redo state, position, tokens

echo $ed->word_at_cursor();
foreach ($ed->completions("str", 8) as $w) { echo $w; }

The workbench, driven headlessly

The workbench owns state and renders it to HTML. A test — or your own tool — builds one with no canvas (0), opens a folder, lays the document out with ensure() and then reads boxes, clicks and key results. tests/positive/ide_workbench.hphp does exactly that.

import "ide";

$wb = new IdeWorkbench(0, 1180, 760, html_theme_dark());
$wb->open_root(".");
$wb->open("lib/ide/workbench.hphp");
$wb->ensure();                          // parse, style, lay out (no ink)

echo $wb->ed()->line_count() . " lines";
echo "code pane: " . $wb->ed_rows() . " rows x " . $wb->ed_cols() . " cols";

$wb->key(80, "", 1);                    // Ctrl+P: the file palette
$wb->key(0, "work", 0);                 // type a query
$wb->key(13, "", 0);                    // Enter: open the first match

Opening it in a window

hphp run holyide/holyide.hphp                 # the current folder
hphp run holyide/holyide.hphp ../my-project   # another one
hphp build holyide/holyide.hphp -o holyide.exe

The app forwards canvas events to key() / mouse(), pumps the running program from a frame timer, follows window resizes and acts on the one string that needs a window: "quit".

Keys

KeysAction
Ctrl+P / Ctrl+Shift+P / Ctrl+Ggo to file · all commands · go to line
Ctrl+S / Ctrl+K Ctrl+Ssave · save all
F5 / Shift+F5 / Ctrl+Rrun the active file · stop · run
Ctrl+Space / Tab / Entercomplete the word at the caret · accept · accept
Ctrl+`the terminal's command line
Ctrl+B / Ctrl+Jtoggle explorer · toggle panel
Ctrl+/ / Ctrl+D / Alt+↑↓toggle comment · duplicate line · move line
Ctrl+= / Ctrl+- / Ctrl+0zoom in · out · reset
Ctrl+Shift+Wquit

What the mouse does

  • A click in the code puts the caret where the pointer is; the gutter picks the whole line. Hold the button and drag to select.
  • A double click selects the word under the pointer.
  • The explorer folds: clicking a folder shows or hides what is in it, clicking a file opens it in a tab.
  • The 5px strip between the explorer and the editor, and between the editor and the panel, is a grip: drag it and that pane changes size. Hovering lights it up, so it can be found.
  • The wheel moves the code one line a notch - it is a scroll, not a jump - and two rows a notch in the explorer.

What runs a file

Ctrl+R starts hphp run <file> through the runtime's proc_* pipe API, in the file's own folder. Output appears in the terminal panel; a failing compile is parsed into the problems list, and clicking a problem opens the file at its line.

The panel is also a terminal, in the small sense: a command line at the bottom, Ctrl+` or a click to focus it, Enter to run through cmd /c in the project folder, Up/Down for history, Tab to hand the keyboard back to the editor. It is a command line over pipes, not a TTY - no interactive prompt, no colours, no full-screen programs.

Status

The workbench is complete and tested headlessly: 100+ assertions cover the editor, the layout numbers, the palette ranking, tabs, the runner and the draw list. The window app exists and passes a pixel self-check (holyide --selftest). What is not there yet — search across files, git, a settings system, split editors, a debugger — is listed in STATUS.md at the repo root, next to the rest of the roadmap.