I Built a C Compiler in PHP That Can Compile SQ...

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest. →

I Built a C Compiler in PHP That Can Compile SQLite

A C frontend written in PHP, an ARM64 target and SQLite.

Interactive version — https://slide.darkwood.com/slides/sqlite-compiler-php

Mathieu Ledru

November 27, 2026

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

44 slides
  1. Darkwood · PHP · C · ARM64 · SQLite I

    Built a C Compiler in PHP That Can Compile SQLite → C frontend → ARM64 → SQLite → PHP → .s → PHP C native @matyo91
  2. The question How much of a C compiler can I

    implement in PHP before it can compile SQLite? 01 | question @matyo91
  3. The result darkwood SQLite 3.46.0 ↓ PHP compiler ↓ ARM64

    ↓ native executable ↓ 46/46 regression fixtures 02 | result @matyo91
  4. What “compiled in PHP” means PHP MACOS Lexer Preprocessor Parser

    AST Sema as linker native executable ARM64 Codegen Clang does not compile sqlite3.c. 03 | boundary @matyo91
  5. Deliberately small source 04 | architecture ↓ tokens ↓ AST

    ↓ typed AST ↓ ARM64 .s No LLVM No SSA No CIR No custom assembler @matyo91
  6. src/Compiler/Driver/Compiler.php The driver $tokens = $preprocessor->preprocess($fileId); $parser = new Parser($tokens,

    $this->diagnostics); $decls = $parser->parse(); $sema = new Sema($this->diagnostics); $tast = $sema->analyze($decls); $codegen = new Codegen($enumConstants); $assembly = $codegen->generate($tast); SOURCE 05 | driver → TOKENS → AST → TYPES → ASM @matyo91
  7. SourceLoc.php Source locations final readonly class SourceLoc { public function

    __construct( public int $fileId, public int $offset, ) {} } fileId + offset 06 | source-loc ↓ SourceManager ↓ line : column @matyo91
  8. Token.php A token is more than text public function __construct(

    public TokenKind $kind, public string $spelling, public SourceLoc $loc, public array $hideSet = [], ) {} Why does a token need a hideSet? 07 | token @matyo91
  9. Slide 9 · 1/2 · représentation statique Macro expansion needs

    memory #define A B #define B A ↓ expand ↓ expand 08 | hide-set Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php A B [hide A] @matyo91
  10. Slide 9 · 2/2 · représentation statique ↓ 08 |

    hide-set Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php A [hide A,B] STOP @matyo91
  11. MacroTable.php · MacroExpander Inside the preprocessor if ($token->hideSet !== []

    && in_array($token->spelling, $token->hideSet, true)) { $output[] = $token; continue; } $newHideSet = $this->unionHideSet($token->hideSet, [$macro->name]); $expanded = $this->expandObjectLike(...); for ($i = count($expanded) - 1; $i >= 0; --$i) { $pendingReversed[] = $expanded[$i]; } 09 | expander @matyo91
  12. The preprocessor is a compiler subsystem #define function macros arguments

    #if / #elif / #else defined() # / ## __VA_ARGS__ rescanning hide sets SQLite never reaches the parser unless this works. 10 | preproc @matyo91
  13. Parsing C by hand No parser generator recursive descent 11

    | parser + Pratt expressions FuncDecl BinaryExpr CallExpr CompoundLiteralExpr @matyo91
  14. C declarators fight back ≠ int *p[4]; array of pointers

    12 | declarators int (*p)[4]; pointer to array @matyo91
  15. Parser::applyArraySuffix() if ($type instanceof PointerCType) { $to = $type->to; $array

    = new ArrayCType($to, $count); return new PointerCType($array); } INT *P[4] INT (*P)[4] Array Pointer └── Pointer └── Array[4] └── int └── int 13 | applyArraySuffix @matyo91
  16. Slide 15 · 1/2 · représentation statique Ast.php The AST

    is just PHP final class BinaryExpr extends Expr { public function __construct( public BinaryOp $op, public Expr $left, public Expr $right, SourceLoc $loc, public ?CType $resolvedType = null, ) {} } 14 | ast Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  17. Slide 15 · 2/2 · représentation statique Ast.php The AST

    is just PHP Parser builds structure. Sema gives it meaning. 14 | ast Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  18. CType.php Representing C types in PHP CType ├── IntCType /

    CharCType / … ├── PointerCType ├── ArrayCType ├── FunctionCType ├── StructCType / UnionCType └── EnumCType $this instanceof EnumCType => true, 15 | ctype // isInteger() @matyo91
  19. Array ≠ pointer — except when it is int a[3];

    int *p = a + 1; ArrayCType remains ↓ expression context pointer-like behavior ↓ + 1 means + sizeof(int) 16 | array-ptr @matyo91
  20. Semantic analysis Scopes Symbols Typedefs Enums Types Conversions $this->enumConstants[$case->name] =

    $case->value; enum { VALUE = 42 }; 17 | sema → .long 42 @matyo91
  21. Global initialization is codegen too ARM64 C _table: static unsigned

    char table[4] = { 84, 92, 134, 0 }; .byte 84 .byte 92 .byte 134 .byte 0 This once became .quad. 18 | globals @matyo91
  22. A PHP namespace bug corrupted C memory instanceof ArrayCType EXPECTED

    PHP RESOLVED App\Compiler\Common\ArrayCTy App\Compiler\CodeGen\ArrayCT pe ype wrong class ↓ wrong branch ↓ .quad ↓ runtime fail It assembled. It linked. It was wrong. 19 | ArrayCType @matyo91
  23. Slide 21 · 1/2 · représentation statique From AST to

    ARM64 int add(int a, int b) { return a + b; } _add: stp x29, x30, [sp, #-16]! mov x29, sp sub sp, sp, #16 str x0, [x29, #-8] str x1, [x29, #-16] … ldrsw … add … 20 | arm64-add Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  24. Slide 21 · 2/2 · représentation statique mov x0, x9

    ldp x29, x30, [sp], #16 ret x0 / x1 args x29 frame · x30 LR x0 return x9–x15 scratch 20 | arm64-add Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  25. Stack frame high ────────────── saved x29 / x30 ────────────── params

    · locals temps · compounds ────────────── SP low sub sp, sp, #0 ; FRAME_SIZE_PLACEHOLDER Patched after emission · 16-byte aligned 21 | frame @matyo91
  26. Pointer arithmetic means scaling int a[3]; a + 1 WRONG

    CORRECT address + 1 × sizeof(int) add x?, x?, #1 lsl …, #2 035-array-ptr-arith 22 | scale @matyo91
  27. Direct vs indirect calls DIRECT bl _function FUNCTION POINTER blr

    xN int call(int (*fn)(int), int value) { return fn(value); } 23 | calls @matyo91
  28. The ABI is where “valid assembly” stops syntax correct ≠

    ABI correct 24 | abi arguments register lifetime stack alignment variadics structs aggregate returns @matyo91
  29. Struct returns use registers too → x0 first word x1

    second word ≤16 bytes struct S b(void) { return a(); } FIX BUG preserve only part of x0/x1 str x0, [...] str x1, [...] 054-struct-return-chain · Loop 48 25 | struct-ret @matyo91
  30. SQLite is an integration oracle SQLite 26 | sqlite Preprocessor

    Declarators Globals Enums Structs / Unions Function pointers Variadic calls ABI Static data @matyo91
  31. Failure Slide 28 · 1/1 · représentation statique → fixture

    → fix SQLite / clang mismatch reduce tiny C fixture find subsystem fix one behavior all fixtures SQLite 27 | methodology Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  32. Slide 29 · 1/2 · représentation statique Bugs became permanent

    knowledge 010char array global 016variadic spill 034compound literal argument 035array pointer arithmetic 044nested designated initializer 28 | fixtures Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  33. Slide 29 · 2/2 · représentation statique 051pointer-to-array 054struct return

    chain Every fixture is a bug the compiler should only have once. 28 | fixtures Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  34. Two different pipelines COMPILER tokens ↓ AST ↓ Sema ↓

    ARM64 OPERATION compile ↓ assemble ↓ link ↓ run ↓ validate Where should Flow live? 29 | two-pipelines @matyo91
  35. Where Darkwood Flow fits COMPILER INTERNALS OPERATIONAL PIPELINE plain PHP

    darkwood/flow yield $this->timed('compile_sqlite', $this->compileSqlite); yield $this->timed('assemble_sqlite', $this->assembleSqlite); yield $this->timed('compile_harness', $this->compileHarness); yield $this->timed('assemble_harness', $this->assembleHarness); yield $this->timed('link', $this->linkSmokeExecutable); yield $this->timed('run', $this->runSmokeTest); 30 | flow @matyo91
  36. Slide 32 · 1/2 · représentation statique One command, many

    artifacts php bin/console app:compiler-sqlite 31 | command Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  37. Slide 32 · 2/2 · représentation statique sqlite3.c harness.c sqlite3.s

    harness.s sqlite3.o harness.o link executable darkwood 31 | command Version interactive : https://slide.darkwood.com/slides/sqlite-compiler-php @matyo91
  38. The engineering loop prob e ↓ exec ute ↓ pare

    ↓ com redu ce ↓ fix ↓ valid ate ↓ KEEP AI becomes useful when it cannot escape the executable feedback loop. 32 | iterate @matyo91
  39. The five-minute wake loop WAKE TICK KEEP resume + probe

    ENGINEERING investigated LOOP change survives validation Loop 48 = last retained engineering change 33 | wake @matyo91
  40. Eventually No mismatch. 46/46 SQLite darkwood → The correct decision

    was to stop changing the compiler. 34 | stop @matyo91
  41. What this proves → ARM64 can PH can host a

    non-trivial Direct frontend P compiler path go surprisingly far SQLi forces subsystems to Feed executable evidence te back beats plausible code 35 | proves become honest @matyo91
  42. What it does NOT prove 36 | limits Not full

    C compliance Not a Clang replacement Not a production compiler Not “AI removes validation” @matyo91
  43. The Darkwood takeaway Compiler algorithms Operational pipelines Correctness 37 |

    takeaway → plain PHP → Darkwood Flow → executable evidence @matyo91
  44. darkwood SQLite ↓ PHP ↓ ARM64 ↓ It assembled. It

    linked. It queried SQLite. @matyo91

More Decks by Mathieu Ledru

Other Decks in Programming