diff --git a/.gitattributes b/.gitattributes index 02f85e03..3eaf9fc7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -12,4 +12,7 @@ /.php-cs-fixer.dist.php export-ignore /codecov.yml export-ignore /rector.php export-ignore -/typephp.php export-ignore \ No newline at end of file +/typephp.php export-ignore +/README.md export-ignore +/CONTRIBUTING.md export-ignore +/SECURITY.md export-ignore \ No newline at end of file diff --git a/README.md b/README.md index 53f3e283..9e7c3b75 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ --- -TypePHP is a Fast transparent, pure-PHP runtime type checker. You don't have to refactor a single line of your codebase, set up complex build toolchains, or compile C-extensions. Simply run your existing code, and TypePHP will enforce your extended PHPDoc contracts (generics, array shapes, `key-of`/`value-of` extractions, and scalar refinements) dynamically at runtime. +TypePHP is a fast, transparent pure-PHP runtime type checker. You don't have to refactor a single line of your codebase, set up complex build toolchains, or compile C-extensions. Simply run your existing code, and TypePHP will enforce your extended PHPDoc contracts (generics, array shapes, `key-of`/`value-of` extractions, and scalar refinements) dynamically at runtime. Run in **Strict Mode** to throw immediate `TypeError` exceptions, or switch to **Audit Report Mode** to collect all runtime type violations across your test suites and legacy codebases into structured JSON reports without interrupting execution. @@ -262,23 +262,34 @@ Supports parallel test runners (**ParaTest**, **Pest Parallel**) with automatic ## Performance: Unbearably Fast Runtime Enforcement -Runtime type checking in pure PHP shouldn't force you to choose between strictness and speed. TypePHP combines **compile-time AST elimination**, **AST-inlined fast-path guards**, **precompiled opcode plans**, **bitmask template inference**, and **optional O(1) hybrid array sampling** and delivering blazing-fast execution even on the heaviest generic codebases. +Runtime type checking in pure PHP shouldn't force you to choose between strictness and speed. TypePHP combines **compile-time AST elimination**, **AST-inlined fast-path guards**, **precompiled opcode plans**, **bitmask template inference**, and **optional O(1) hybrid array sampling** to deliver blazing-fast execution on both everyday web applications and heavy generic libraries. -### Real-World Stress Benchmark ([`noctud/collection`](https://github.com/noctud/collection)) +### Real-World Laravel Application (Typical I/O-Bound Workload) -Tested against `noctud/collection` (**6,928 tests, 12,510 assertions**) this a worst-case, pure-CPU benchmark packed with `@template` inference, variance rules, `WeakMap` reified generics, conditional return types, fluent `self` chains, iterables, and closures: +Tested on a real-world Laravel application (**430 tests, 2,652 assertions**, **216 instrumented application files** running via `php artisan test --compact` with warm cache): + +| Mode | Duration | Overhead | +| --- | --- | --- | +| **TypePHP Disabled (`TYPEPHP_DISABLE=true`)** | `54.46s` | — | +| **TypePHP Enabled** | `55.12s` | **`+0.66s` (~1.2%)** | + +In typical web frameworks (**Laravel**, **Symfony**, **Shopware**) where database queries, HTTP routing, container bootstrapping, and I/O dominate execution time, TypePHP's runtime overhead is **negligible (~1%)**—practically indistinguishable from normal run-to-run variance. + +### Pure-CPU Stress Benchmark ([`noctud/collection`](https://github.com/noctud/collection)) + +Tested against `noctud/collection` (**6,928 tests, 12,510 assertions**) this is a worst-case, pure-CPU benchmark with zero I/O, packed with `@template` inference, variance rules, `WeakMap` reified generics, conditional return types, fluent `self` chains, typed iterables, and typed closures: | Mode | Native PHP (`TYPEPHP_DISABLE=true`) | Early TypePHP | TypePHP Now | Wall-Time Speedup | Overhead Eliminated | | --- | --- | --- | --- | --- | --- | -| **Sequential (`phpunit`)** | `00:06.554` (`82 MB`) | `02:41.013` (`108 MB`) | `00:29.440` (`128 MB`) | **5.47× faster** | **−85.2%** (`154.5s` → `22.9s`) | +| **Sequential (`phpunit`)** | `00:06.554` (`82 MB`) | `02:41.013` (`108 MB`) | `00:23.463` (`130 MB`) | **6.86× faster** | **−89.1%** (`154.5s` → `16.9s`) | | **Parallel (`paratest -p4`)** | `00:02.001` (`62 MB`) | `01:26.168` (`62 MB`) | `00:07.780` (`62 MB`) | **11.08× faster** | **−93.1%** (`84.2s` → `5.8s`) | -Running full runtime generics and PHPDoc contract enforcement across nearly 7,000 collection tests completes in **under 8 seconds** in parallel and adding less than **6 seconds** over raw native PHP. +Even in this extreme pure-CPU generics stress test, running full runtime reified generics and PHPDoc contract enforcement across nearly 7,000 collection tests completes in **under 8 seconds** in parallel, adding less than **6 seconds** over raw native PHP. ### How TypePHP Stays Fast -* **Compile-Time Static Elimination:** Provably satisfied contracts (literals, trusted unmutated parameters, constants, exact non-generic instantiations) are eliminated during AST transformation and costing **0 ns** at runtime. +* **Compile-Time Static Elimination:** Provably satisfied contracts (literals, trusted unmutated parameters, constants, exact non-generic instantiations) are eliminated during AST transformation, costing **0 ns** at runtime. * **AST-Inlined Guards & Disk Caching:** Transformed files are cached to disk (and OPcache-ready) with inline `isset()` short-circuits so unconstrained or non-contracted methods skip runtime calls entirely. -* **Precompiled Opcode Plans & Flat Call Frames:** Parameter, return, `class-string`, and generic iterable checks execute against precompiled integer opcodes, bitmasks, and flat O(1) frame arrays rather than re-interpreting DocBlock ASTs. +* **Precompiled Opcode Plans & Flat Call Frames:** Parameter, return, `class-string`, and generic iterable checks execute against precompiled local integer opcodes (`ZEND_MATCH` jump tables), bitmasks, and flat O(1) frame arrays rather than re-interpreting DocBlock ASTs. * **Configurable Array Strategy (`full` vs `hybrid`):** Use `'array_validation' => 'full'` for 100% exhaustive O(n) scans, or switch to `'hybrid'` for Beartype-inspired O(1) boundary + random sampling on massive arrays (`> 128` items). --- diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 409fcc3d..b81f42c1 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -1634,6 +1634,26 @@ public static function bindInstanceFromNode( self::resolveInheritedTemplates($instance, $className); } + if (! $forceBind && ! $allowBoundSpecialization && ! $refineOnly) { + $defaults = self::$classTemplateDefaultsCache[$actualClass] ?? self::classTemplateDefaults($actualClass); + if ($defaults !== []) { + self::$instanceTemplateBindings ??= new WeakMap(); + $currentInstBindings = self::$instanceTemplateBindings[$instance] ?? []; + $defaultsApplied = false; + + foreach ($defaults as $defName => $defType) { + if (! isset($currentInstBindings[$defName])) { + $currentInstBindings[$defName] = $defType; + $defaultsApplied = true; + } + } + + if ($defaultsApplied) { + self::$instanceTemplateBindings[$instance] = $currentInstBindings; + } + } + } + $existingBindings = self::$instanceTemplateBindings !== null ? (self::$instanceTemplateBindings[$instance] ?? null) : null; diff --git a/src/Internal/Reporting/ViolationCollector.php b/src/Internal/Reporting/ViolationCollector.php index 564bc171..943994f8 100644 --- a/src/Internal/Reporting/ViolationCollector.php +++ b/src/Internal/Reporting/ViolationCollector.php @@ -41,6 +41,14 @@ final class ViolationCollector private static bool $shutdownRegistered = false; + /** + * Tracks how many occurrences of each violation hash this process has already merged + * into a given report file path, preventing double-counting on repeated exportReport() calls. + * + * @var array> + */ + private static array $exportedCountsByTarget = []; + /** * Resets in-memory state. Useful for test isolation. */ @@ -49,6 +57,7 @@ public static function reset(): void self::$violations = []; self::$warnedHashes = []; self::$propertyLineCache = []; + self::$exportedCountsByTarget = []; self::$shutdownRegistered = false; } @@ -167,6 +176,7 @@ public static function clear(): void self::$violations = []; self::$warnedHashes = []; self::$propertyLineCache = []; + self::$exportedCountsByTarget = []; } /** @@ -275,7 +285,8 @@ public static function writeWorkerShard(string $reportFile): void } /** - * Merges in-memory violations with any worker shards and atomically exports the master report JSON. + * Merges in-memory violations, any existing report on disk, and worker shards + * under an exclusive file lock, then writes the consolidated master report JSON. */ public static function exportReport(?string $filePath = null): ?string { @@ -287,22 +298,169 @@ public static function exportReport(?string $filePath = null): ?string $reportDir = \dirname($targetFile); $shardDir = $reportDir . '/.typephp-shards'; - $allViolations = self::consolidateShards(self::$violations, $shardDir); - if (! is_dir($reportDir)) { @mkdir($reportDir, 0777, true); } - $document = self::buildReportDocument($allViolations); - $json = json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE); + $normalizedTarget = str_replace('\\', '/', $targetFile); + $fp = @fopen($targetFile, 'c+b'); - if ($json === false || @file_put_contents($targetFile, $json) === false) { - return null; + if ($fp === false) { + $allViolations = self::consolidateShards(self::$violations, $shardDir); + $document = self::buildReportDocument($allViolations); + $json = json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE); + + if ($json === false || @file_put_contents($targetFile, $json) === false) { + return null; + } + + return $targetFile; + } + + $locked = @flock($fp, LOCK_EX); + + try { + $existingViolations = []; + $existingInstrumentedCount = 0; + + rewind($fp); + $existingRaw = stream_get_contents($fp); + if (\is_string($existingRaw) && trim($existingRaw) !== '') { + [$existingViolations, $existingInstrumentedCount] = self::parseExistingReport($existingRaw); + } + + $hadShards = is_dir($shardDir); + $hasNewDeltas = false; + $merged = $existingViolations; + $exportedForTarget = self::$exportedCountsByTarget[$normalizedTarget] ?? []; + + foreach (self::$violations as $hash => $record) { + $alreadyExported = $exportedForTarget[$hash] ?? 0; + $delta = $record->count - $alreadyExported; + + if ($delta > 0) { + $hasNewDeltas = true; + if (isset($merged[$hash])) { + $merged[$hash] = $merged[$hash]->withIncrementedCount($delta); + } else { + $merged[$hash] = $delta === $record->count + ? $record + : new ViolationRecord( + file: $record->file, + line: $record->line, + function: $record->function, + kind: $record->kind, + target: $record->target, + expected: $record->expected, + given: $record->given, + message: $record->message, + count: $delta, + caller: $record->caller, + declaredIn: $record->declaredIn + ); + } + $exportedForTarget[$hash] = $record->count; + } elseif (! isset($merged[$hash])) { + $hasNewDeltas = true; + $merged[$hash] = $record; + $exportedForTarget[$hash] = $record->count; + } + } + + self::$exportedCountsByTarget[$normalizedTarget] = $exportedForTarget; + + $allViolations = self::consolidateShards($merged, $shardDir); + $instrumentedCount = max($existingInstrumentedCount, StreamWrapper::getInstrumentedCount()); + + if ( + \is_string($existingRaw) + && trim($existingRaw) !== '' + && ! $hasNewDeltas + && ! $hadShards + && $instrumentedCount === $existingInstrumentedCount + ) { + return $targetFile; + } + + $document = self::buildReportDocument($allViolations, $instrumentedCount); + $json = json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE); + + if ($json === false) { + return null; + } + + rewind($fp); + ftruncate($fp, 0); + $written = fwrite($fp, $json); + fflush($fp); + + if ($written === false) { + return null; + } + } finally { + if ($locked) { + @flock($fp, LOCK_UN); + } + fclose($fp); } return $targetFile; } + /** + * Parses an existing master report JSON payload into deduplicated records and its instrumented file count. + * + * @return array{0: array, 1: int} + */ + private static function parseExistingReport(string $raw): array + { + /** @var array|null $decoded */ + $decoded = json_decode($raw, true); + if (! \is_array($decoded)) { + return [[], 0]; + } + + /** @var array $violations */ + $violations = []; + if (isset($decoded['violations']) && \is_array($decoded['violations'])) { + foreach ($decoded['violations'] as $item) { + if (! \is_array($item)) { + continue; + } + + /** @var array $item */ + $record = ViolationRecord::fromArray($item); + if ($record === null) { + continue; + } + + $hash = $record->getHash(); + $violations[$hash] = isset($violations[$hash]) + ? $violations[$hash]->withIncrementedCount($record->count) + : $record; + } + } + + $instrumentedCount = 0; + if ( + isset($decoded['summary']) + && \is_array($decoded['summary']) + && isset($decoded['summary']['files_instrumented']) + && \is_int($decoded['summary']['files_instrumented']) + ) { + $instrumentedCount = max(0, $decoded['summary']['files_instrumented']); + } elseif ( + isset($decoded['context']) + && \is_array($decoded['context']) + && isset($decoded['context']['files_instrumented']) + && \is_int($decoded['context']['files_instrumented']) + ) { + $instrumentedCount = max(0, $decoded['context']['files_instrumented']); + } + + return [$violations, $instrumentedCount]; + } + /** * @param array $baseViolations * @@ -392,7 +550,7 @@ private static function mergeShardContent(array $allViolations, string $raw): ar * violations: list * } */ - private static function buildReportDocument(array $violations): array + private static function buildReportDocument(array $violations, ?int $instrumentedCount = null): array { $violationsList = array_values($violations); $filesAffected = []; @@ -400,7 +558,7 @@ private static function buildReportDocument(array $violations): array $filesAffected[$v->file] = true; } - $instrumentedCount = StreamWrapper::getInstrumentedCount(); + $instrumentedCount ??= StreamWrapper::getInstrumentedCount(); $configFile = Config::getResolvedConfigFile(); $projectRoot = Config::getProjectRoot(); diff --git a/tests/Internal/Reporting/ViolationReportMergeSafetyTest.php b/tests/Internal/Reporting/ViolationReportMergeSafetyTest.php new file mode 100644 index 00000000..972d24a7 --- /dev/null +++ b/tests/Internal/Reporting/ViolationReportMergeSafetyTest.php @@ -0,0 +1,135 @@ + 'report', 'report_file' => $reportFile]); + for ($i = 0; $i < 216; $i++) { + StreamWrapper::recordInstrumentedFile("app/Services/Service{$i}.php"); + } + $err = new ErrorMessage("App\\Services\\PatientService::formatPatientDetails(): Return value key must be of type float, string 'id' returned"); + for ($i = 0; $i < 6; $i++) { + ViolationCollector::handle($err, 'return', [], 'app/Services/PatientService.php', 206); + } + ViolationCollector::exportReport($reportFile); + + ViolationCollector::reset(); + StreamWrapper::reset(); + for ($i = 0; $i < 14; $i++) { + StreamWrapper::recordInstrumentedFile("app/Providers/Provider{$i}.php"); + } + ViolationCollector::exportReport($reportFile); + + $doc = json_decode((string) file_get_contents($reportFile), true); + + expect($doc['summary']['total_violations'])->toBe(1) + ->and($doc['summary']['files_affected'])->toBe(1) + ->and($doc['summary']['files_instrumented'])->toBe(216) + ->and($doc['context']['files_instrumented'])->toBe(216) + ->and($doc['violations'])->toHaveCount(1) + ->and($doc['violations'][0]['count'])->toBe(6) + ; + } finally { + @unlink($reportFile); + @rmdir($tempDir); + } + }); + + test('merges and aggregates violation counts across sequential processes writing to the same report file', function () { + $tempDir = sys_get_temp_dir() . '/typephp_report_merge_' . uniqid(); + mkdir($tempDir, 0777, true); + $reportFile = $tempDir . '/typephp_audit.json'; + + try { + Config::set(['on_violation' => 'report', 'report_file' => $reportFile]); + + $errA = new ErrorMessage('App\\Payment::charge(): Argument $amount must be of type positive-int, negative int (-10) given'); + for ($i = 0; $i < 3; $i++) { + ViolationCollector::handle($errA, 'parameter', -10, 'app/Payment.php', 20); + } + ViolationCollector::exportReport($reportFile); + + ViolationCollector::reset(); + for ($i = 0; $i < 2; $i++) { + ViolationCollector::handle($errA, 'parameter', -10, 'app/Payment.php', 20); + } + $errB = new ErrorMessage("App\\User::setName(): Argument \$name must be of type non-empty-string, empty string ('') given"); + ViolationCollector::handle($errB, 'parameter', '', 'app/User.php', 45); + ViolationCollector::exportReport($reportFile); + + $doc = json_decode((string) file_get_contents($reportFile), true); + + expect($doc['summary']['total_violations'])->toBe(2) + ->and($doc['summary']['files_affected'])->toBe(2) + ; + + $byFile = []; + foreach ($doc['violations'] as $v) { + $byFile[$v['file']] = $v; + } + + expect($byFile['app/Payment.php']['count'])->toBe(5) + ->and($byFile['app/User.php']['count'])->toBe(1) + ; + } finally { + @unlink($reportFile); + @rmdir($tempDir); + } + }); + + test('does not double-count violations when exportReport() is called multiple times within the same process', function () { + $tempDir = sys_get_temp_dir() . '/typephp_report_idempotent_' . uniqid(); + mkdir($tempDir, 0777, true); + $reportFile = $tempDir . '/typephp_audit.json'; + + try { + Config::set(['on_violation' => 'report', 'report_file' => $reportFile]); + $err = new ErrorMessage('App\\Order::pay(): Argument $id must be of type positive-int, negative int (-1) given'); + + for ($i = 0; $i < 4; $i++) { + ViolationCollector::handle($err, 'parameter', -1, 'app/Order.php', 10); + } + + ViolationCollector::exportReport($reportFile); + ViolationCollector::exportReport($reportFile); + + $doc1 = json_decode((string) file_get_contents($reportFile), true); + expect($doc1['violations'][0]['count'])->toBe(4); + + ViolationCollector::handle($err, 'parameter', -1, 'app/Order.php', 10); + ViolationCollector::handle($err, 'parameter', -1, 'app/Order.php', 10); + ViolationCollector::exportReport($reportFile); + + $doc2 = json_decode((string) file_get_contents($reportFile), true); + expect($doc2['violations'][0]['count'])->toBe(6); + } finally { + @unlink($reportFile); + @rmdir($tempDir); + } + }); +}); diff --git a/tests/TypeChecking/Generics/DefaultTemplateParameterBoundaryTest.php b/tests/TypeChecking/Generics/DefaultTemplateParameterBoundaryTest.php new file mode 100644 index 00000000..715a611d --- /dev/null +++ b/tests/TypeChecking/Generics/DefaultTemplateParameterBoundaryTest.php @@ -0,0 +1,158 @@ + + */ + public function login(): void + { + } + + /** + * @self-out self<'unauthenticated'> + */ + public function logout(): void + { + } +} + +final class DefaultTypestateSubSession extends DefaultTypestateSession +{ +} + +final class DefaultTemplateCustomPayload +{ +} + +/** + * @template T of object = stdClass + */ +final class DefaultObjectGenericBox +{ +} + +/** + * @param DefaultTypestateSession<'authenticated'> $session + */ +function accessDefaultTypestateDashboard(DefaultTypestateSession $session): string +{ + return 'granted'; +} + +/** + * @param DefaultTypestateSession<'unauthenticated'> $session + */ +function accessDefaultTypestateLoginPage(DefaultTypestateSession $session): string +{ + return 'login'; +} + +/** + * @return DefaultTypestateSession<'authenticated'> + */ +function returnForgedDefaultSession(): DefaultTypestateSession +{ + return new DefaultTypestateSession(); +} + +/** + * @param DefaultObjectGenericBox $box + */ +function acceptCustomPayloadDefaultBox(DefaultObjectGenericBox $box): bool +{ + return true; +} + +/** + * @param DefaultObjectGenericBox $box + */ +function acceptStdClassDefaultBox(DefaultObjectGenericBox $box): bool +{ + return true; +} + +describe('Default Generic Template Enforcement at Call Boundaries', function () { + test('rejects passing unannotated new Session() (default unauthenticated) into authenticated-only function', function () { + $session = new DefaultTypestateSession(); + + expect(TypePHP::getGenericType($session))->toBe("'unauthenticated'"); + + expect(fn () => accessDefaultTypestateDashboard($session)) + ->toThrow(TypeError::class, "DefaultTypestateSession, but " . DefaultTypestateSession::class . "<'unauthenticated'> was given") + ; + + expect(accessDefaultTypestateLoginPage($session))->toBe('login'); + }); + + test('enforces full typestate lifecycle without @var (blocked -> login -> allowed -> logout -> blocked)', function () { + $session = new DefaultTypestateSession(); + + expect(fn () => accessDefaultTypestateDashboard($session)) + ->toThrow(TypeError::class) + ; + + $session->login(); + expect(TypePHP::getGenericType($session))->toBe("'authenticated'") + ->and(accessDefaultTypestateDashboard($session))->toBe('granted') + ; + + $session->logout(); + expect(TypePHP::getGenericType($session))->toBe("'unauthenticated'"); + + expect(fn () => accessDefaultTypestateDashboard($session)) + ->toThrow(TypeError::class) + ; + }); + + test('still allows explicit specialization via inline @var at instantiation', function () { + /** @var DefaultTypestateSession<'authenticated'> $session */ + $session = new DefaultTypestateSession(); + + expect(TypePHP::getGenericType($session))->toBe("'authenticated'") + ->and(accessDefaultTypestateDashboard($session))->toBe('granted') + ; + }); + + test('rejects returning bare new Session() when @return requires authenticated state', function () { + expect(fn () => returnForgedDefaultSession()) + ->toThrow(TypeError::class, "'authenticated'") + ; + }); + + test('enforces default object template (= stdClass) at parameter boundary while allowing explicit @var specialization', function () { + $freshBox = new DefaultObjectGenericBox(); + + expect(fn () => acceptCustomPayloadDefaultBox($freshBox)) + ->toThrow(TypeError::class, DefaultTemplateCustomPayload::class) + ; + + expect(acceptStdClassDefaultBox($freshBox))->toBeTrue(); + + /** @var DefaultObjectGenericBox $specializedBox */ + $specializedBox = new DefaultObjectGenericBox(); + expect(acceptCustomPayloadDefaultBox($specializedBox))->toBeTrue(); + }); + + test('enforces inherited default generic template on subclasses without @var', function () { + $subSession = new DefaultTypestateSubSession(); + + expect(fn () => accessDefaultTypestateDashboard($subSession)) + ->toThrow(TypeError::class, "'unauthenticated'") + ; + + $subSession->login(); + expect(accessDefaultTypestateDashboard($subSession))->toBe('granted'); + }); +});