Skip to content

Commit 29db1b3

Browse files
committed
add blog post for TypePHP v0.12.0 release and update index links
1 parent 07ab2e0 commit 29db1b3

3 files changed

Lines changed: 479 additions & 82 deletions

File tree

‎docs/.vitepress/data/posts.json‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
11
[
2+
{
3+
"title": "TypePHP v0.12.0: The Zero-Overhead Compile-Time Optimization Engine",
4+
"url": "/blog/celebrating-v0.12.0-compile-time-optimization-engine",
5+
"date": "October 28, 2026",
6+
"readTime": "6 min read",
7+
"badge": "Release",
8+
"badgeClass": "badge-announcement",
9+
"excerpt": "Celebrating v0.12.0! Featuring Compile-Time AST Check Elimination, lexical zero line-drift parsing, by-reference mutation tracking, and backed Enum bitmasks."
10+
},
211
{
312
"title": "The 'No More DocBlocks' Illusion: Why Native Generics Would Never Kill the Comment Tax in PHP",
413
"url": "/blog/the-no-more-docblocks-illusion",
Lines changed: 369 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,369 @@
1+
---
2+
title: "TypePHP v0.12.0: The Zero-Overhead Compile-Time Optimization Engine"
3+
description: "Celebrating v0.12.0! Introducing Compile-Time AST Check Elimination, live in-browser WebAssembly snippets, the 'Inverse TypeScript' model, and deep by-reference mutation defense."
4+
date: 2026-10-28
5+
author: Reymart Calicdan
6+
layout: doc
7+
sidebar: false
8+
aside: true
9+
prev: false
10+
next: false
11+
---
12+
13+
# TypePHP v0.12.0: The Zero-Overhead Compile-Time Optimization Engine
14+
15+
<div class="blog-post-meta" style="margin-bottom: 24px;">
16+
<span class="blog-badge badge-announcement">Release</span>
17+
<span>October 28, 2026</span>
18+
<span class="dot">•</span>
19+
<span>8 min read</span>
20+
</div>
21+
22+
Today, I am thrilled to announce the release of **TypePHP v0.12.0**.
23+
24+
Alongside this release, I have rolled out a complete redesign of the documentation and enginering blog. Every guide is now equipped with **interactive, executable code snippets running real PHP 8.5 in your browser via WebAssembly**. You no longer have to take my word for how runtime generics or shape validations behave; you can click **Run**, inspect the transformed bytecode, and tweak inputs live on every page.
25+
26+
Before diving into the benchmarks, I have a humorous confession to share about what TypePHP actually is under the hood.
27+
28+
---
29+
30+
## The Dirty Confession: TypePHP is an "Inverse TypeScript" Transpiler
31+
32+
I often describe TypePHP with the tagline: *"Zero build steps, zero transpilation, pure PHP."*
33+
34+
While that is true from a developer ergonomics perspective (you never run Webpack, Babel, or Node.js), looking at the computer science definition reveals an amusing reality:
35+
36+
> **TypePHP is technically a source-to-source transpiler, much like TypeScript, but operating in reverse.**
37+
38+
Consider the architectural contrast:
39+
* **TypeScript** takes rich types at build time and **erases** them into untyped vanilla JavaScript for runtime execution.
40+
* **TypePHP** does the oposite: it takes passive DocBlock comments and **reifies** them into active runtime guard rails inside memory.
41+
42+
```mermaid
43+
flowchart LR
44+
subgraph TS["TypeScript Model"]
45+
A["`**Strict Types**
46+
*(Source Code)*`"] -->|Transpiles via Erasure| B["`**Untyped JS**
47+
*(Runtime)*`"]
48+
end
49+
50+
subgraph TP["TypePHP Model"]
51+
C["`**Passive DocBlocks**
52+
*(Source Code)*`"] -->|Transpiles via Reification| D["`**Strict Memory**
53+
*(Runtime Guard Rails)*`"]
54+
end
55+
56+
style A fill:#3b82f6,color:#fff,stroke-width:0px
57+
style B fill:#64748b,color:#fff,stroke-width:0px
58+
style C fill:#f59e0b,color:#fff,stroke-width:0px
59+
style D fill:#10b981,color:#fff,stroke-width:0px
60+
```
61+
62+
What about the *"no build step"* claim?
63+
64+
Technically, **TypePHP does have a hidden build step; it is simply Just-In-Time (JIT) by default.**
65+
66+
When PHP loads a file, TypePHP’s `StreamWrapper` intercepts the `include` stream, parses the AST, folds static expressions, and injects guard rails on-the-fly right before the Zend Engine compiles it to OPcache bytecode.
67+
68+
For teams that prefer **Ahead-Of-Time (AOT) transpilation** during production deployments, you run:
69+
```bash
70+
vendor/bin/typephp cache:warm
71+
# or
72+
vendor/bin/typephp cache:rebuild
73+
```
74+
This pre-transpiles every included PHP file on disk ahead of time. You get all the safety of a compiled type system without ever leaving pure PHP userland.
75+
76+
Now, let us examine the core innovation of v0.12.0: making this transpiler run at **100% native C-speed**.
77+
78+
---
79+
80+
## 1. Flagship: Compile-Time AST Check Elimination
81+
82+
The biggest historical criticism of runtime type systems is **performance overhead**. If every single getter, property default, and return statement is blindly wrapped in runtime assertion functions, high-throughput loops pay an unnecessary Zend VM call tax.
83+
84+
In **v0.12.0**, I eliminated that tax entirely with **Compile-Time AST Check Elimination**.
85+
86+
When a method returns a literal like `'2.0.0'` against `@return non-empty-string`, or `60 * 60` against `@return positive-int`, or `$this` on a fluent builder, **evaluating that contract at runtime is completely redundant**. The statement is mathematically and syntactically proven safe before the code ever executes.
87+
88+
Starting in v0.12.0, TypePHP's new `StaticTypeEvaluator` analyzes statement expresions against their declared contracts during load-time file transformation. If an expression is statically proven safe:
89+
90+
> **TypePHP completely skips injecting runtime assertion wrappers for that statement.**
91+
92+
### The Benchmark Difference
93+
94+
| Execution Strategy | What Zend VM Executes | Speed | JIT Compatibility |
95+
| :--- | :--- | :--- | :--- |
96+
| **Traditional Runtime Wrapping** | Pushes arguments to stack $\to$ calls `checkReturn()` $\to$ evaluates `T_INSTANCEOF` $\to$ ternary branch (~50 opcodes). | ~800k calls/sec | JIT refuses to inline dynamic calls |
97+
| **TypePHP v0.12.0 Check Elimination** | **Single `ZEND_RETURN` opcode**. Emits raw, clean PHP. | **~25M+ calls/sec (Native C-Speed)** | **Tracing JIT can inline the leaf method directly.** |
98+
99+
### Test Drive It Live (Inspect the Transformed Source)
100+
101+
Click the **Transformed** tab in the snippet below to inspect the compiled AST. Notice that `getTtl()` and `selfChain()` have **zero assertion wrappers injected**, while the dynamic calculation preserves full runtime guard rails:
102+
103+
<TypePHPSnippet title="Compile-Time AST Elimination in Action" default-view="transformed">
104+
105+
```php:line-numbers
106+
<?php
107+
108+
declare(strict_types=1);
109+
110+
class CacheConfig
111+
{
112+
/** @return positive-int */
113+
public function getTtl(): int
114+
{
115+
// 60 * 60 folds to 3600 at compile time: proven positive-int, so the check is omitted!
116+
return 60 * 60;
117+
}
118+
119+
/** @return $this */
120+
public function selfChain(): self
121+
{
122+
// $this identity is an absolute truth: check omitted! Fluent chaining runs at native speed.
123+
return $this;
124+
}
125+
126+
/** @return positive-int */
127+
public function dynamicTtl(int $multiplier): int
128+
{
129+
// Dynamic variable multiplication: unverifiable at compile time, so runtime check is injected!
130+
return $multiplier * 60;
131+
}
132+
}
133+
134+
$config = new CacheConfig();
135+
echo "Static TTL: " . $config->getTtl() . "s\n";
136+
echo "Dynamic TTL: " . $config->dynamicTtl(5) . "s\n";
137+
```
138+
139+
</TypePHPSnippet>
140+
141+
### What Gets Eliminated?
142+
* **Scalar & Range Literals:** `return 42;` vs `@return positive-int`, `return 50;` vs `@return int<1, 100>`.
143+
* **String Concatenations:** `return 'item_' . $id;` vs `@return non-empty-string` (prefix guarantees length $\ge 5$).
144+
* **Constant & Enum Wildcards:** `return self::STATUS_ACTIVE;` vs `@return self::STATUS_*`.
145+
* **Empty Arrays:** `return [];` vs `@return list<T>` or `array<K, V>`.
146+
* **Sequential Lists & Shapes:** `return [1, 2, 3];` vs `list<int>`, `['id' => 1]` vs `array{id: int}`.
147+
* **Exact Object Instantiations:** `return new User('Alice');` vs `@return User` (exact FQCN string match, zero reflection).
148+
* **Property Defaults:** `public int $timeout = 30;` vs `@var positive-int` (bypasses constructor synthesis).
149+
150+
---
151+
152+
## 2. Interactive Code Everywhere (Docs & Blog)
153+
154+
Reading static code blocks in developer documentation is often passive and unconvincing. With v0.12.0, I overhauled the documentation and blog architecture to run on an embedded **PHP 8.5 WebAssembly engine**.
155+
156+
Every code example across the guides and release posts now allows you to:
157+
1. **Execute live in your browser:** Tap **Run** and watch the real Zend Engine validate inputs in milliseconds.
158+
2. **Inspect the Transformed AST:** Toggle **Transformed** to see exactly what TypePHP injects (and what it statically eliminates).
159+
3. **Inspect the Error Output:** Trigger contract violations and inspect real PHP stack traces with exact call-site line attribution.
160+
4. **Share Compact Snippets:** Share links that are 80% smaller or backed by instant shortlinks (`typephp.dev/#r=...`).
161+
162+
---
163+
164+
## 3. Backed Enum Bitmasks (`int-mask-of<Permission::*>`)
165+
166+
In v0.12.0, I resolved an edge case where bitmasks referencing Backed Enums (`enum Permission: int`) were not correctly extracting integer case values during bitwise validation.
167+
168+
TypePHP now seamlessly resolves bitwise combinations of backed enum cases:
169+
170+
<TypePHPSnippet title="Backed Enum Bitmasks in v0.12.0" default-view="source">
171+
172+
```php:line-numbers
173+
<?php
174+
175+
declare(strict_types=1);
176+
177+
enum Permission: int
178+
{
179+
case Read = 1; // 0001
180+
case Write = 2; // 0010
181+
case Delete = 4; // 0100
182+
}
183+
184+
/**
185+
* @param int-mask-of<Permission::*> $mask
186+
*/
187+
function applyAccess(int $mask): void
188+
{
189+
echo "✓ Valid bitmask combination applied: {$mask}\n";
190+
}
191+
192+
// 1. Happy Path: 3 = Read (1) | Write (2)
193+
applyAccess(Permission::Read->value | Permission::Write->value);
194+
195+
// 2. Happy Path: 7 = Read (1) | Write (2) | Delete (4)
196+
applyAccess(7);
197+
198+
echo "\n";
199+
200+
// 3. Failure: 8 is outside any Permission case combination!
201+
echo "Attempting to pass unapproved bitmask 8...\n";
202+
applyAccess(8);
203+
```
204+
205+
</TypePHPSnippet>
206+
207+
---
208+
209+
## 4. Lexical Token Parsing for Robust Zero Line-Drift
210+
211+
A critical architectural guarantee of TypePHP is **Zero Line-Drift**: stack traces in Laravel Ignition, Whoops, Symfony ErrorHandler, Pest, and PHPUnit must point to the **exact line number** of your original source file.
212+
213+
In previous versions, squashing multi-line assertions into single-line blocks relied on regular expressions. In complex edge cases (such as multiline strings containing `#` or `//`), regex could misinterpret comments inside string literals.
214+
215+
In v0.12.0, I replaced regex comment handling with **PHP 8.0+ Lexical Token Parsing** (`\PhpToken::tokenize()`). The printer tokenizes the source code at C-level speed, safely neutralizing trailing comments preceding injected assertions without any risk of corrupting string literals.
216+
217+
---
218+
219+
## 5. The Danger of By-Reference Mutations in PHP (And How v0.12.0 Solves It)
220+
221+
In PHP, references (`&`) represent one of the most surprising, bug-prone language features.
222+
223+
When you create a reference in PHP, the Zend Engine transforms the underlying variable into an internal `zval` alias (`IS_REFERENCE`). Once aliased, any modification to the alias bypasses standard variable assignment interceptors completely:
224+
225+
```php
226+
/**
227+
* @var list<positive-int> $scores
228+
*/
229+
$scores = [10, 20, 30];
230+
231+
// The classic PHP footgun:
232+
foreach ($scores as &$score) {
233+
if ($score === 20) {
234+
$score = -500; // Sneakily corrupts list<positive-int> in place!
235+
}
236+
}
237+
unset($score);
238+
```
239+
240+
In standard PHP, no exception is thrown when `$score = -500` runs. The container is silently poisoned with negative numbers, quietly propagating through your services until it causes catastrophic calculation errors downstream.
241+
242+
Similarly, consider **deep member aliasing**:
243+
```php
244+
$ref =& $data['user']['scores'];
245+
$ref[] = 'corrupted_string'; // Directly mutates nested shape without touching root variable!
246+
```
247+
248+
### The Solution in v0.12.0
249+
250+
In v0.12.0, I completely overhauled TypePHP's reference analysis engine:
251+
252+
1. **Loop Boundary Post-Assertions:** When a by-reference loop (`foreach ($items as &$item)`) executes, TypePHP analyzes the loop body. If there is any risk of opaque mutations, an atomic post-boundary check is injected immediately following the loop, guaranteeing that memory corruption is caught before control leaves the scope.
253+
2. **Compile-Time Loop Optimization:** If static AST analysis proves that the loop body contains only safe mathematical operations (e.g., `$score += 5` on `positive-int`), the boundary check is **completely omitted at compile time**, allowing safe loops to run at native C-speed.
254+
3. **Atomic Deep Member-Chain Tracking:** Accessor chains (`$data['user']['scores'][] = ...`) are unpacked into isolated copy mutations and validated atomically before writing to memory.
255+
256+
Try running the by-reference mutation protection live below:
257+
258+
<TypePHPSnippet title="By-Reference Mutation Defense" default-view="source">
259+
260+
```php:line-numbers
261+
<?php
262+
263+
declare(strict_types=1);
264+
265+
/**
266+
* @var positive-int $originalScore
267+
*/
268+
$originalScore = 100;
269+
270+
// Create reference alias
271+
$alias =& $originalScore;
272+
273+
// Valid mutation through alias:
274+
$alias += 50;
275+
echo "✓ Valid mutation via alias: Score={$originalScore}\n\n";
276+
277+
// In standard PHP, mutating $alias directly bypasses assignment checks!
278+
// TypePHP tracks the reference target and guards the underlying zval at compile time
279+
// and injects a post-boundary check to catch illegal mutations:
280+
281+
echo "Attempting to assign negative value via reference alias...\n";
282+
$alias = -75;
283+
284+
```
285+
286+
</TypePHPSnippet>
287+
288+
---
289+
290+
## 6. Enhanced Generic Cloning (`__clone`)
291+
292+
When cloning a generic object (`clone $instance`), TypePHP binds template parameters in `\WeakMap` memory.
293+
294+
In earlier versions, a subtle lifecycle timing gap existed: if a class defined a custom `__clone()` magic method, that method ran *before* external listeners could re-bind template types to the newly cloned object. Any property assignments made *inside* `__clone()` could execute in an unparameterized generic context!
295+
296+
In v0.12.0, I hardened the lifecycle hooks. TypePHP now guarantees that **template bindings are copied to the new instance in `\WeakMap` memory before magic `__clone()` begins execution**.
297+
298+
Click **Run** below to observe how TypePHP protects property assignments performed inside `__clone()`:
299+
300+
<TypePHPSnippet title="Generic Safety Inside __clone() Magic Methods" default-view="source">
301+
302+
```php:line-numbers
303+
<?php
304+
305+
declare(strict_types=1);
306+
307+
class Dog {}
308+
class Vehicle {}
309+
310+
/**
311+
* @template T
312+
*/
313+
class SmartBox
314+
{
315+
/** @var T|null */
316+
public mixed $item = null;
317+
318+
/** @param T $item */
319+
public function set(mixed $item): void
320+
{
321+
$this->item = $item;
322+
}
323+
324+
public function __clone(): void
325+
{
326+
echo "Executing __clone() hook...\n";
327+
// TypePHP pre-copied T = Dog before this method ran!
328+
// Attempting to assign an invalid Vehicle inside __clone() is blocked instantly:
329+
$this->set(new Vehicle());
330+
}
331+
}
332+
333+
/** @var SmartBox<Dog> $box */
334+
$box = new SmartBox();
335+
$box->set(new Dog());
336+
echo "✓ Initialized SmartBox with Dog\n\n";
337+
338+
// Cloning triggers __clone(), where TypePHP actively enforces T = Dog:
339+
echo "Cloning SmartBox...\n";
340+
$clonedBox = clone $box;
341+
342+
```
343+
344+
</TypePHPSnippet>
345+
346+
---
347+
348+
## Upgrading to v0.12.0
349+
350+
To upgrade to v0.12.0 in your project:
351+
352+
```bash
353+
composer update typephp/typephp
354+
```
355+
356+
Clear and rebuild your AST cache to take immediate advantage of compile-time check elimination:
357+
358+
```bash
359+
vendor/bin/typephp cache:rebuild
360+
```
361+
362+
If you have not tried TypePHP yet, you can add it as a development dependency in seconds:
363+
364+
```bash
365+
composer require --dev typephp/typephp
366+
vendor/bin/typephp config:init
367+
```
368+
369+
Give it a spin in your Pest or PHPUnit test suite, experiment with the new code snippets live in our [Interactive WebAssembly Playground](/playground), and let me know what you think on [GitHub](https://github.com/typephp-php/typephp)!

0 commit comments

Comments
 (0)