### Running Examples with Cargo Source: https://github.com/illegalstudio/elephc/blob/main/CLAUDE.md Demonstrates how to execute specific examples using the Cargo build tool. ```bash cargo run -- examples/fizzbuzz/main.php ``` -------------------------------- ### Running Examples Directly Source: https://github.com/illegalstudio/elephc/blob/main/CLAUDE.md Shows how to execute examples directly after compilation. ```bash ./examples/fizzbuzz/main ``` -------------------------------- ### PHP Fiber Example Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/fibers.md Demonstrates the basic usage of PHP Fibers, including starting, suspending, and resuming with arguments. Shows the flow of execution and data transfer between the caller and the fiber. ```php start(); // one echo "|"; echo $counter->resume("alpha"); // resumed with alpha two echo "|"; echo $counter->resume("beta"); // resumed with beta three ?> ``` -------------------------------- ### Running Elephc Examples Source: https://github.com/illegalstudio/elephc/blob/main/AGENTS.md Commands to execute examples using the Cargo build tool or directly after compilation. ```bash cargo run -- examples/fizzbuzz/main.php ``` ```bash ./examples/fizzbuzz/main ``` -------------------------------- ### Fiber Example Source: https://github.com/illegalstudio/elephc/blob/main/README.md A basic example of using Fibers for cooperative multitasking. ```php $fiber = new Fiber(function (): void { $value = Fiber::suspend(1); echo "Fiber received: ", $value, "\n"; }); $fiber->start(); $fiber->resume(2); ``` -------------------------------- ### Compile and Run PHP Regex Program Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/regex.md Example of a PHP script using `preg_match` and the commands to compile and run it with Elephc. No manual linking flags are typically needed if PCRE2 is installed. ```php x = 10; ``` ```php Counter::$count = 10; ``` ```php self::$count = 10; ``` ```php Counter::$items[] = 10; ``` ```php self::$items[] = 10; ``` ```php Counter::$items[0] = 10; ``` ```php self::$items[0] = 10; ``` ```php $p->items[] = 10; ``` ```php $p->items[0] = 10; ``` ```php extern function foo(int $x): int; ``` ```php extern class Point { public int $x; } ``` ```php extern global ptr $environ; ``` ```php my_func(); ``` -------------------------------- ### Verify elephc Installation Source: https://github.com/illegalstudio/elephc/blob/main/docs/getting-started/installation.md Compiles and runs a simple PHP script to confirm elephc is installed and functional. ```bash echo ' check.php elephc check.php && ./check ``` -------------------------------- ### PHP Source Code Example Source: https://github.com/illegalstudio/elephc/blob/main/docs/internals/the-lexer.md Illustrates a simple PHP code snippet that will be tokenized. ```php 5) { echo "big\n"; } ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/illegalstudio/elephc/blob/main/docs/getting-started/installation.md Installs essential tools like the assembler and linker required for building native binaries on macOS. ```bash xcode-select --install ``` -------------------------------- ### Testing HTTP Server Routes Source: https://github.com/illegalstudio/elephc/blob/main/showcases/http-server/README.md Examples of how to test different routes of the running HTTP server using curl. ```bash curl http://127.0.0.1:8080/ curl 'http://127.0.0.1:8080/hello?name=elephc' curl http://127.0.0.1:8080/json curl http://127.0.0.1:8080/stats ``` -------------------------------- ### Buffer Operations Source: https://github.com/illegalstudio/elephc/blob/main/README.md Illustrates creating, getting length, and freeing a buffer. ```php $buffer = buffer_new(10); $len = buffer_len($buffer); echo "Buffer length: ", $len, "\n"; buffer_free($buffer); ``` -------------------------------- ### Exercise Server Routes with cURL Source: https://github.com/illegalstudio/elephc/blob/main/docs/how-to/fiber-web-server.md Examples of using cURL to send requests to different routes of the running HTTP server. ```bash curl http://127.0.0.1:8080/ ``` ```bash curl 'http://127.0.0.1:8080/hello?name=elephc' ``` ```bash curl http://127.0.0.1:8080/json ``` ```bash curl http://127.0.0.1:8080/stats ``` -------------------------------- ### Asymmetric Visibility Example Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/classes.md Shows how to use asymmetric visibility for a property, allowing it to be publicly readable but privately writable. This restricts where the property can be modified. ```php value = $this->value + 1; // allowed: write from inside the class } } $c = new Counter(); $c->increment(); echo $c->value; // 2 — public read // $c->value = 9; // rejected: write is private ``` -------------------------------- ### PHP Built-in Function Examples Source: https://github.com/illegalstudio/elephc/blob/main/README.md Illustrates the usage of various PHP built-in functions for strings, arrays, and math. ```php echo strlen("example"); print_r(array_keys(['a' => 1, 'b' => 2])); echo abs(-5); ``` -------------------------------- ### AArch64 Assembly for Example Source: https://github.com/illegalstudio/elephc/blob/main/docs/internals/how-elephc-works.md This AArch64 assembly code represents the compiled output for a simplified example after control flow pruning. It demonstrates stack frame setup, variable assignment, string output, and system calls for writing to stdout and exiting. ```asm .global _main .align 2 _main: ; -- prologue: set up stack frame -- sub sp, sp, #32 stp x29, x30, [sp, #16] add x29, sp, #16 ; -- $x = 10 -- mov x0, #10 stur x0, [x29, #-8] ; -- echo "big\n" (the if shell was pruned earlier) -- adrp x1, _str_0@PAGE add x1, x1, _str_0@PAGEOFF mov x2, #4 ; length = 4 ("big" + newline) mov x0, #1 ; fd = stdout mov x16, #4 ; syscall = write svc #0x80 ; call kernel ; -- epilogue: exit(0) -- mov x0, #0 mov x16, #1 svc #0x80 .data _str_0: .ascii "big\n" ``` -------------------------------- ### Manual Build and Run Source: https://github.com/illegalstudio/elephc/blob/main/showcases/http-server/README.md Manual steps to build the PHP code into a native binary and then run the server. ```bash cargo run -- showcases/http-server/main.php ./showcases/http-server/main ``` -------------------------------- ### Minimal C host example Source: https://github.com/illegalstudio/elephc/blob/main/docs/beyond-php/cdylib.md A minimal C program demonstrating how to load a cdylib using `dlopen`, retrieve function pointers using `dlsym`, and call exported PHP functions. It includes calling lifecycle entry points. ```c #include #include #include int main(void) { void *lib = dlopen("./libauth.so", RTLD_NOW | RTLD_LOCAL); int32_t (*init)(void) = dlsym(lib, "elephc_init"); int64_t (*add)(int64_t, int64_t) = dlsym(lib, "add_i64"); int32_t (*validate)(const char *, size_t) = dlsym(lib, "validate_token"); init(); printf("%lld\n", (long long)add(40, 2)); // 42 printf("%d\n", validate("supersecret", 11)); // 0 return 0; } ``` -------------------------------- ### Compile and Run Hello World in PHP Source: https://github.com/illegalstudio/elephc/blob/main/docs/getting-started/your-first-program.md Compile a simple PHP 'Hello, World!' script into a standalone native binary using elephc and then execute it. ```php path = $path; file_put_contents($this->path, "scratch"); } public function __destruct() { unlink($this->path); // runs automatically when the object is released } } ``` -------------------------------- ### PDO Database Connection and Query Source: https://github.com/illegalstudio/elephc/blob/main/README.md Demonstrates establishing a PDO connection and executing a query with named binds. ```php $pdo = new PDO('sqlite::memory:'); $pdo->exec('CREATE TABLE users (id INTEGER, name TEXT)'); $pdo->exec("INSERT INTO users (name) VALUES ('Alice'), ('Bob')"); $stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name'); $stmt->execute([':name' => 'Alice']); while ($row = $stmt->fetch()) { print_r($row); } ``` -------------------------------- ### Install PCRE2 Development Package on macOS Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/regex.md Installs the PCRE2 development package on macOS using Homebrew. This is a prerequisite for compiling programs that use regex. ```bash brew install pcre2 ``` -------------------------------- ### Basic Class Instantiation Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/classes.md Demonstrates the basic instantiation of a PHP class using the 'new' keyword. ```php $p = new Point(3, 4); ``` -------------------------------- ### Build and Run HTTP Server Source: https://github.com/illegalstudio/elephc/blob/main/showcases/http-server/README.md Helper script to build and run the elephc HTTP server. It also includes options for testing and building only. ```bash ./showcases/http-server/build.sh run ./showcases/http-server/build.sh test ./showcases/http-server/build.sh ``` -------------------------------- ### Build and Run on Linux Source: https://github.com/illegalstudio/elephc/blob/main/examples/cdylib/README.md Commands to compile the PHP file into a cdylib and then compile and run the C host program. ```bash cargo run -- --emit cdylib examples/cdylib/auth.php cc -o examples/cdylib/host examples/cdylib/host.c -ldl ./examples/cdylib/host examples/cdylib/libauth.so ``` -------------------------------- ### PSR-0 / Custom Autoloader Example Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/namespaces.md An example of a custom autoloader using spl_autoload_register that replaces backslashes with underscores for file paths. This autoloader is evaluated at compile time. ```php Void flags(main) { entry: v0: Str php=string own=persistent = const_str str[0] echo v0 ; effects: output return } } ``` -------------------------------- ### Variable and Identifier Token Examples Source: https://github.com/illegalstudio/elephc/blob/main/docs/internals/the-lexer.md Examples of variable and identifier tokens. Variables are prefixed with '$' and carry the name without the symbol, while identifiers represent names of functions or other entities. ```text Variable: $x, $name, $argc Identifier: strlen, my_func ``` -------------------------------- ### Install PCRE2 Development Package on Arch Linux Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/regex.md Installs the PCRE2 development package on Arch Linux using pacman. This is needed for compiling programs that incorporate regex. ```bash sudo pacman -S pcre2 ``` -------------------------------- ### Using SplMaxHeap and SplPriorityQueue Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/spl.md Demonstrates inserting elements into a max heap and a priority queue, and extracting them. Shows how to set extract flags for SplPriorityQueue. ```php insert(3); $heap->insert(1); $heap->insert(5); while (!$heap->isEmpty()) { echo $heap->extract(); } $queue = new SplPriorityQueue(); $queue->insert("low", 1); $queue->insert("high", 10); $queue->setExtractFlags(SplPriorityQueue::EXTR_BOTH); $item = $queue->extract(); echo $item["data"]; echo $item["priority"]; ?> ``` -------------------------------- ### Install PCRE2 Development Package on Debian/Ubuntu Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/regex.md Installs the PCRE2 development package on Debian or Ubuntu systems using apt. This is necessary for compiling programs that use regex. ```bash sudo apt install libpcre2-dev ``` -------------------------------- ### Install PCRE2 Development Package on Alpine Linux Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/regex.md Installs the PCRE2 development package on Alpine Linux using apk. This is required for compiling programs that utilize regex functionality. ```bash apk add pcre2-dev ``` -------------------------------- ### DatePeriod Constructor Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/datetime.md Constructs a DatePeriod object. It can be built over a date range [start, end) or for a specific recurrence count. Options can be provided to modify the inclusivity of the start and end dates. ```APIDOC ## DatePeriod::__construct ### Description Build a period either over `[start, end)` or for an integer recurrence count. ### Method `__construct(DateTimeInterface $start, DateInterval $interval, DateTimeInterface|int $end, int $options = 0)` ### Parameters #### Path Parameters - **start** (DateTimeInterface) - Required - The starting date of the period. - **interval** (DateInterval) - Required - The interval between dates. - **end** (DateTimeInterface|int) - Required - The end date of the period or the recurrence count. - **options** (int) - Optional - Flags to modify period behavior, e.g., `DatePeriod::EXCLUDE_START_DATE`, `DatePeriod::INCLUDE_END_DATE`. ### Request Example ```php // Using end date $period = new DatePeriod( new DateTime("2024-01-01"), new DateInterval("P1M"), new DateTime("2024-04-01") ); // Using recurrence count $p = new DatePeriod(new DateTime("2024-01-01"), new DateInterval("P1D"), 3); // With options $p = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE); ``` ### Response #### Success Response (200) An iterator yielding `DateTime` objects representing each step in the period. #### Response Example ```php foreach ($period as $dt) { echo $dt->format("Y-m-d"), "\n"; } // Output for the first example: // 2024-01-01 // 2024-02-01 // 2024-03-01 ``` ``` -------------------------------- ### Build and Run Elephc Compiler Source: https://github.com/illegalstudio/elephc/blob/main/CLAUDE.md Commands to build the Elephc compiler in development or release mode, and to compile a PHP file into a native binary. ```bash cargo build # dev build ``` ```bash cargo build --release # optimized build ``` ```bash cargo run -- file.php # compile a PHP file ``` -------------------------------- ### Build and Run on macOS Source: https://github.com/illegalstudio/elephc/blob/main/examples/cdylib/README.md Commands to compile the PHP file into a cdylib and then compile and run the C host program. ```bash cargo run -- --emit cdylib examples/cdylib/auth.php cc -o examples/cdylib/host examples/cdylib/host.c ./examples/cdylib/host examples/cdylib/libauth.dylib ``` -------------------------------- ### Literal Token Examples Source: https://github.com/illegalstudio/elephc/blob/main/docs/internals/the-lexer.md Examples of integer, float, and string literals recognized by the lexer. These tokens carry specific values of type i64 or f64, or string content after escape resolution. ```text IntLiteral: 42, 0xFF, 0755, 0o755, 0b1010, 1_000_000 FloatLiteral: 3.14, .5, 1e3, 1_000.5, 1e1_0 StringLiteral: "hello", 'world' ``` -------------------------------- ### Get Image Size from String Data Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/image.md Utilize getimagesizefromstring to get image information directly from a string containing image data. This avoids the need to save the data to a temporary file. ```php $data = file_get_contents("photo.png"); $info = getimagesizefromstring($data); if ($info !== false) { echo $info[0] . "x" . $info[1] . " " . $info["mime"]; // 800x600 image/png } ``` -------------------------------- ### Dynamic Method and Static Calls in PHP Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/classes.md Shows how to call instance methods and static methods using variable names for the method or class. Supports brace syntax for clarity. ```php $method(2, 3); // 5 — dynamic instance method echo $calc->{$method}(2, 3); // 5 — brace form $class = "Calculator"; echo $class::version(); // 1.0 — dynamic static call $static = "version"; echo $class::$static(); // 1.0 — both class and method dynamic ?> ``` -------------------------------- ### Constant Propagation Example in Elephc Source: https://github.com/illegalstudio/elephc/blob/main/docs/internals/how-elephc-works.md This example demonstrates how constant propagation can simplify a conditional statement. The pass forwards the assignment of '10' to '$x' into the 'if' condition, effectively turning 'true' into a literal. ```php getSize(); echo $fixed[0]; $fixed->setSize(3); $fixed[2] = "tail"; ``` -------------------------------- ### EIR Example with Block Parameters Source: https://github.com/illegalstudio/elephc/blob/main/docs/internals/the-ir.md An example demonstrating block parameters in Elephc Intermediate Representation (EIR). This function calculates the sum of numbers up to a given input, using labeled blocks and parameter passing. ```eir function sum_to(p0: I64 php=int) -> I64 { entry: v0: I64 php=int = const_i64 0 v1: I64 php=int = const_i64 1 br loop(v1, v0) loop(i: I64 php=int, acc: I64 php=int): v2: I64 php=bool = icmp sle i, p0 cond_br v2, body(i, acc), exit(acc) body(i: I64 php=int, acc: I64 php=int): v3: I64 php=int = iadd acc, i v4: I64 php=int = iadd i, 1 br loop(v4, v3) exit(result: I64 php=int): return result } ``` -------------------------------- ### Benchmarking HTTP Server with ApacheBench Source: https://github.com/illegalstudio/elephc/blob/main/showcases/http-server/README.md Command to benchmark the HTTP server's latency using ApacheBench. ```bash ab -n 100 http://127.0.0.1:8080/ ``` -------------------------------- ### Pure Pipe Operator Examples Source: https://github.com/illegalstudio/elephc/blob/main/docs/internals/the-optimizer.md Illustrates constant folding for pure pipe operator expressions with whitelisted built-in functions. These examples demonstrate how literal scalar values are folded into their final results at compile time. ```php "hello" |> strlen(...) ``` ```php 3.7 |> floor(...) ``` ```php "hello" |> strtoupper(...) |> strrev(...) ``` ```php 5 |> is_int(...) ``` ```php 5 |> gettype(...) ``` -------------------------------- ### PHP Property with Get and Set Hooks Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/classes.md Implements a 'celsius' property with get and set hooks that interact with a private backing field '$c'. Use for properties that require custom logic on read or write operations. ```php $this->c; set { $this->c = $value; } } public float $fahrenheit { get => $this->c * 9.0 / 5.0 + 32.0; set { $this->c = ($value - 32.0) * 5.0 / 9.0; } } } $t = new Thermostat(); $t->fahrenheit = 212.0; echo $t->celsius; // 100 ?> ``` -------------------------------- ### Basic Compilation and Execution Source: https://github.com/illegalstudio/elephc/blob/main/docs/compiling/overview.md Compile a PHP file and then run the resulting executable. The compiler outputs the binary next to the source file, named after the source without its extension. ```bash elephc hello.php ./hello ``` -------------------------------- ### Rust: Emitter Instruction with Comments Source: https://github.com/illegalstudio/elephc/blob/main/CLAUDE.md Demonstrates correct formatting for emitter.instruction calls with inline and block comments. Ensure comments explain intent and are aligned properly. ```rust // -- set up stack frame -- emitter.instruction("sub sp, sp, #32"); // allocate 32 bytes on the stack emitter.instruction("stp x29, x30, [sp, #16]"); // save frame pointer and return address emitter.instruction("add x29, sp, #16"); // set new frame pointer // -- convert integer to string and write to stdout -- emitter.instruction("bl __rt_itoa"); // convert x0 to decimal string → x1=ptr, x2=len emitter.instruction("mov x0, #1"); // fd = stdout emitter.instruction("mov x16, #4"); // syscall 4 = sys_write emitter.instruction("svc #0x80"); // invoke macOS kernel ``` -------------------------------- ### Array Functions Source: https://github.com/illegalstudio/elephc/blob/main/README.md Examples of array manipulation functions. ```php $arr = [1, 2, 3]; echo implode(", ", $arr); // 1, 2, 3 $str = "a,b,c"; print_r(explode(",", $str)); // Array ( [0] => a [1] => b [2] => c ) ``` -------------------------------- ### DatePeriod::getStartDate Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/datetime.md Retrieves the start date that was used to construct the DatePeriod. ```APIDOC ## DatePeriod::getStartDate ### Description Returns the start date of the period. ### Method `getStartDate(): DateTime` ### Parameters None ### Response #### Success Response (200) - **DateTime** - The start date of the period. ``` -------------------------------- ### Make Downloaded Binary Executable Source: https://github.com/illegalstudio/elephc/blob/main/docs/getting-started/installation.md Grants execute permissions to a downloaded elephc binary artifact. ```bash chmod +x elephc ``` -------------------------------- ### elephc Compilation Process Source: https://github.com/illegalstudio/elephc/blob/main/docs/internals/what-is-a-compiler.md Shows how elephc transforms a PHP source file into a native executable. ```text hello.php → elephc → hello (native executable) → runs directly on CPU ``` -------------------------------- ### Type Checking Functions Source: https://github.com/illegalstudio/elephc/blob/main/README.md Examples of ctype functions for character type checking. ```php echo ctype_alpha('abc'); // 1 (true) echo ctype_digit('123'); // 1 (true) echo ctype_space(' '); // 1 (true) ``` -------------------------------- ### Create Image Surface and Draw Arc Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/image.md Demonstrates creating an image surface, setting up a Cairo context, drawing a filled arc with a specific color, and saving the result to a PNG file. ```php $surface = cairo_image_surface_create(CairoFormat::ARGB32, 160, 120); $cr = cairo_create($surface); cairo_set_source_rgb($cr, 1, 1, 1); cairo_paint($cr); cairo_set_source_rgb($cr, 0.114, 0.306, 0.847); cairo_arc($cr, 48, 60, 34, 0, 2 * M_PI); cairo_fill($cr); cairo_surface_write_to_png($surface, "out.png"); ``` -------------------------------- ### DateTime and DateInterval Usage Source: https://github.com/illegalstudio/elephc/blob/main/README.md Example of creating and manipulating DateTime objects with DateInterval. ```php $date = new DateTime('2023-10-26'); $interval = new DateInterval('P1Y2M'); // 1 year, 2 months $date->add($interval); echo $date->format('Y-m-d') . "\n"; ``` -------------------------------- ### Type and Emptiness Checking Source: https://github.com/illegalstudio/elephc/blob/main/ROADMAP.md Get the type of a variable or check if it is considered empty. ```PHP gettype() ``` ```PHP settype() ``` ```PHP empty() ``` -------------------------------- ### Basic DateTime Manipulation and Formatting Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/datetime.md Demonstrates creating a DateTime object, setting its date and time, formatting it, and adding a DateInterval. Also shows how DateTimeImmutable returns a new instance after modification. ```php $dt = new DateTime(); $dt->setDate(2024, 1, 15); $dt->setTime(9, 30, 0); echo $dt->format("Y-m-d H:i:s"); // 2024-01-15 09:30:00 $dt->add(new DateInterval("P1Y2M10D")); echo $dt->format("Y-m-d"); // 2025-03-25 // DateTimeImmutable returns a fresh instance; the original is unchanged. $base = (new DateTimeImmutable())->setDate(2024, 1, 15)->setTime(0, 0, 0); $later = $base->add(new DateInterval("PT2H30M")); echo $base->format("H:i:s"); // 00:00:00 echo $later->format("H:i:s"); // 02:30:00 ``` -------------------------------- ### Array Merging and Slicing in ElephC Source: https://github.com/illegalstudio/elephc/blob/main/ROADMAP.md Provides examples of merging, slicing, and splicing arrays. ```PHP array_merge(), array_slice(), array_splice() ``` -------------------------------- ### Connect to SQLite, PostgreSQL, and MySQL Databases Source: https://github.com/illegalstudio/elephc/blob/main/docs/php/pdo.md Demonstrates how to establish connections to different database types using PDO. Supports file-backed or in-memory SQLite databases, and PostgreSQL/MySQL with credentials provided either in the DSN or as constructor arguments. ```php