From 05bb6e1e18aca795b56ca51d61e5b920a85943c4 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 11:28:19 +0800 Subject: [PATCH 01/15] Fix discovered edge cases during routine manual qa testing --- composer.json | 5 + .../Elimination/EliminationSafetyPolicy.php | 12 +- src/Internal/Ast/FunctionContractInjector.php | 6 +- src/Internal/Checker/InlineChecker.php | 108 ++++- src/Internal/Checker/ParamChecker.php | 40 +- src/Internal/Checker/ParamOutChecker.php | 2 +- src/Internal/Checker/ReturnChecker.php | 77 +++- src/Internal/Docblock/DocblockNormalizer.php | 82 ++-- src/Internal/Generics/TemplateManager.php | 295 ++++++++++-- src/Internal/Io/CacheManager.php | 7 +- src/Internal/Io/StreamWrapper.php | 138 +++++- src/Internal/RuntimeTypeChecker.php | 70 ++- src/Internal/Wrapper/CallableWrapper.php | 8 + tests/Feature/ViolationConfigModeTest.php | 45 ++ .../Docblock/DocblockNormalizerTest.php | 101 +++++ tests/Internal/Io/CacheManagerTest.php | 12 +- tests/Internal/Io/StreamWrapperTest.php | 142 ++++++ .../RuntimeTypeCheckerSimplePlanTest.php | 111 +++++ .../CallableWrapperVariadicIgnoreTest.php | 138 ++++++ .../Generics/InlineVarUnboundFallbackTest.php | 165 +++++++ .../Generics/InterfaceGenericVarianceTest.php | 420 ++++++++++++++++++ 21 files changed, 1836 insertions(+), 148 deletions(-) create mode 100644 tests/Feature/ViolationConfigModeTest.php create mode 100644 tests/Internal/RuntimeTypeCheckerSimplePlanTest.php create mode 100644 tests/Internal/Wrapper/CallableWrapperVariadicIgnoreTest.php create mode 100644 tests/TypeChecking/Generics/InlineVarUnboundFallbackTest.php create mode 100644 tests/TypeChecking/Generics/InterfaceGenericVarianceTest.php diff --git a/composer.json b/composer.json index 47ab3767..9d446650 100644 --- a/composer.json +++ b/composer.json @@ -60,6 +60,11 @@ ] }, "scripts": { + "qa": [ + "./vendor/bin/pint --parallel", + "./vendor/bin/phpstan analyze", + "./vendor/bin/pest --compact" + ], "format": [ "./vendor/bin/pint" ], diff --git a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php index dd6bc3ba..c20eba60 100644 --- a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php +++ b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php @@ -61,11 +61,13 @@ final class EliminationSafetyPolicy * and scalar generics (int, int-mask) which carry no object state. * 3. Authorizes standalone functions, closures, and arrow functions (zero inheritance risk). * 4. For class methods: - * - Authorizes private methods, final methods, and methods on final classes. - * - Authorizes classes with no inheritance (`hasRealInheritance === false`). - * 5. Defers all other methods to runtime to prevent bypassing unanalyzed parent contracts. + * - Authorizes private methods. + * - Rejects trait methods (`isTrait === true`) since traits may be composed into inheriting classes. + * - Authorizes classes with no real inheritance (`hasRealInheritance === false`). + * 5. Defers all other methods (including final methods/classes with inheritance) to runtime + * to prevent bypassing unanalyzed parent or interface contracts. * - * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool}|null $classContext */ public static function isReturnEliminationSafe( ClassMethod|Function_|Closure|ArrowFunction $functionNode, @@ -106,7 +108,7 @@ public static function isReturnEliminationSafe( /** * Determines whether generator yield, send, and return checks can be safely eliminated under LSP rules. * - * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext + * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool, isTrait?: bool}|null $classContext */ public static function isGeneratorEliminationSafe( ClassMethod|Function_|Closure|ArrowFunction $functionNode, diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 46cdc7dd..9f22ddc3 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -444,7 +444,11 @@ private static function collectTrustedParamTypes( return []; } - if (Config::getOnViolation() !== 'throw' || ! Config::isParamsEnabled()) { + if ( + ! Config::isEliminateStaticallyProvenChecksEnabled() + || Config::getOnViolation() !== 'throw' + || ! Config::isParamsEnabled() + ) { return []; } diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 5d5904e2..c618759b 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -50,9 +50,9 @@ final class InlineChecker private static array $parsedTypeNodeCache = []; /** - * In-memory 3D cache for resolved class contexts with static bounds: [$className][$methodName][$typeString] => TypeNode. + * In-memory 3D cache for resolved class contexts with static bounds: [$className][$methodName][$typeString] => array{0: TypeNode, 1: array{0: int, 1: array}}. * - * @var array>> + * @var array}}>>> */ private static array $resolvedClassContextCache = []; @@ -89,7 +89,7 @@ final class InlineChecker /** * In-memory cache for resolved instance property generic types per object instance. * - * @var \WeakMap, props: array}>|null + * @var \WeakMap, fallbackKeys: array, props: array, fallbacks?: array}>}>|null */ private static ?\WeakMap $instancePropertyTypeCache = null; @@ -112,6 +112,7 @@ public static function reset(): void self::$propertyUsesTemplatesCache = []; self::$classHasSelfOutCache = []; self::$resolvedStaticPropertyTypeCache = []; + self::$instancePropertyTypeCache = null; } /** @@ -189,8 +190,9 @@ public static function checkVariable( ??= SpecialTypeResolver::resolveForFile($typeNode, $file, $callerNamespace); } + $fallbackMeta = [0, []]; if ($needsContext && $caller !== null) { - $typeNode = self::resolveCallerContext($typeNode, $caller, $thisOrClass); + [$typeNode, $fallbackMeta] = self::resolveCallerContextWithFallback($typeNode, $caller, $thisOrClass); } if (! self::shouldValidateType($typeNode)) { @@ -216,6 +218,11 @@ public static function checkVariable( } } + $preExistingBindings = null; + if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $typeNode instanceof GenericTypeNode) { + $preExistingBindings = TemplateManager::$instanceTemplateBindings[$value] ?? []; + } + if ($typeNode instanceof GenericTypeNode && Config::isInlineGenericsEnabled() && \is_object($value)) { $err = TemplateManager::bindInstanceFromNode($value, $typeNode, $context); if ($err !== null) { @@ -228,6 +235,10 @@ public static function checkVariable( return $err; } + if ($preExistingBindings !== null && \is_object($value) && $typeNode instanceof GenericTypeNode) { + TemplateManager::markFallbackReturnBindings($value, $typeNode, $fallbackMeta[1], $fallbackMeta[0], $preExistingBindings); + } + if ($typeNode instanceof CallableTypeNode || ($typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'callable')) { $cbPrefix = ($varName === 'return') ? 'Return value: Callback' : "Variable \$$varName: Callback"; @@ -508,11 +519,12 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string $propertyUsesTemplates = false; $typeNode = $rawTypeNode; + $fallbackMeta = [0, []]; if (\is_object($objectOrClass)) { $propertyUsesTemplates = self::propertyUsesTemplates($rawTypeNode, $className, $propName); if ($propertyUsesTemplates) { - $typeNode = self::substitutePropertyGenerics($rawTypeNode, $objectOrClass, $className); + [$typeNode, $fallbackMeta] = self::substitutePropertyGenericsWithFallback($rawTypeNode, $objectOrClass, $className, $propName); } } elseif (\is_string($objectOrClass)) { $propertyUsesTemplates = self::propertyUsesTemplates($rawTypeNode, $className, $propName); @@ -521,6 +533,11 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string } } + $preExistingBindings = null; + if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $typeNode instanceof GenericTypeNode) { + $preExistingBindings = TemplateManager::$instanceTemplateBindings[$value] ?? []; + } + try { $err = $registry->validate($value, $typeNode, 'Property ' . $className . '::$' . $propName); if ($err !== null) { @@ -535,6 +552,10 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string return $err; } + + if ($preExistingBindings !== null && \is_object($value) && $typeNode instanceof GenericTypeNode) { + TemplateManager::markFallbackReturnBindings($value, $typeNode, $fallbackMeta[1], $fallbackMeta[0], $preExistingBindings); + } } catch (\Throwable $e) { // Silently ignore unexpected execution exceptions } @@ -682,17 +703,25 @@ private static function trySelfOutTransition(mixed $value, object $object, strin * Resolves caller class or function context and applies templates & type aliases to the AST. */ private static function resolveCallerContext(TypeNode $typeNode, ?string $caller = null, mixed $thisOrClass = null): TypeNode + { + return self::resolveCallerContextWithFallback($typeNode, $caller, $thisOrClass)[0]; + } + + /** + * @return array{0: TypeNode, 1: array{0: int, 1: array}} + */ + private static function resolveCallerContextWithFallback(TypeNode $typeNode, ?string $caller = null, mixed $thisOrClass = null): array { if ($caller !== null) { if ($caller === '') { - return $typeNode; + return [$typeNode, [0, []]]; } if (str_contains($caller, '::')) { [$className, $methodName] = explode('::', $caller, 2); $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - return self::resolveClassContext( + return self::resolveClassContextWithFallback( $typeNode, $className, $methodName, @@ -700,21 +729,25 @@ private static function resolveCallerContext(TypeNode $typeNode, ?string $caller ); } - return self::resolveFunctionContext($typeNode, $caller); + return self::resolveFunctionContextWithFallback($typeNode, $caller); } - return $typeNode; + return [$typeNode, [0, []]]; } /** * Resolves templates and aliases within standalone functions. + * + * @return array{0: TypeNode, 1: array{0: int, 1: array}} */ - private static function resolveFunctionContext(TypeNode $typeNode, string $functionName): TypeNode + private static function resolveFunctionContextWithFallback(TypeNode $typeNode, string $functionName): array { if (! \function_exists($functionName)) { - return $typeNode; + return [$typeNode, [0, []]]; } + $fallbackMeta = [0, []]; + try { $refFunc = new \ReflectionFunction($functionName); $typeNode = SpecialTypeResolver::resolve($typeNode, $refFunc); @@ -727,6 +760,7 @@ private static function resolveFunctionContext(TypeNode $typeNode, string $funct $activeBindings = [...$aliases, ...$boundTemplates]; if (\count($activeBindings) > 0 || \count($declaredTemplates) > 0) { + $fallbackMeta = TemplateManager::collectUnboundGenericArgIndices($typeNode, $activeBindings, $declaredTemplates); $typeNode = TemplateSubstitutor::substitute($typeNode, $activeBindings, $declaredTemplates); $typeNode = SpecialTypeResolver::resolve($typeNode, $refFunc); } @@ -734,18 +768,20 @@ private static function resolveFunctionContext(TypeNode $typeNode, string $funct // Silently continue if reflection fails } - return $typeNode; + return [$typeNode, $fallbackMeta]; } /** * Resolves templates, aliases, and class context within class methods using zero-allocation nested caching. + * + * @return array{0: TypeNode, 1: array{0: int, 1: array}} */ - private static function resolveClassContext( + private static function resolveClassContextWithFallback( TypeNode $typeNode, string $className, ?string $methodName, ?object $thisObj - ): TypeNode { + ): array { if ( ! class_exists($className, false) && ! interface_exists($className, false) @@ -754,7 +790,7 @@ private static function resolveClassContext( && ! interface_exists($className) && ! trait_exists($className) ) { - return $typeNode; + return [$typeNode, [0, []]]; } $targetFunc = ($methodName !== '{closure}' && $methodName !== null && ! str_starts_with($methodName, '{closure')) @@ -775,6 +811,8 @@ private static function resolveClassContext( } } + $fallbackMeta = [0, []]; + try { /** @var class-string $className */ $refClass = new \ReflectionClass($className); @@ -785,17 +823,23 @@ private static function resolveClassContext( $declaredTemplates = $allTemplates; if ($classAliases === [] && $declaredTemplates === []) { + $result = [$typeNode, [0, []]]; if ($canCache && $typeString !== null) { - return self::$resolvedClassContextCache[$className][$methodKey][$typeString] = $typeNode; + return self::$resolvedClassContextCache[$className][$methodKey][$typeString] = $result; } - return $typeNode; + return $result; } $boundTemplates = TemplateManager::getBoundTemplates($targetFunc, $thisObj, $declaredTemplates); $activeBindings = [...$classAliases, ...$boundTemplates]; if ($activeBindings !== [] || $declaredTemplates !== []) { + $thisFallbackKeys = $thisObj !== null ? TemplateManager::getFallbackBoundTemplates($thisObj) : []; + $concreteBindings = $thisFallbackKeys !== [] + ? array_diff_key($activeBindings, $thisFallbackKeys) + : $activeBindings; + $fallbackMeta = TemplateManager::collectUnboundGenericArgIndices($typeNode, $concreteBindings, $declaredTemplates); $typeNode = TemplateSubstitutor::substitute($typeNode, $activeBindings, $declaredTemplates); $typeNode = SpecialTypeResolver::resolve($typeNode, $refClass); } @@ -803,25 +847,35 @@ private static function resolveClassContext( // Silently continue if reflection fails } + $result = [$typeNode, $fallbackMeta]; if ($canCache && $typeString !== null) { - return self::$resolvedClassContextCache[$className][$methodKey][$typeString] = $typeNode; + return self::$resolvedClassContextCache[$className][$methodKey][$typeString] = $result; } - return $typeNode; + return $result; } /** * Substitutes generic template types declared on class properties. */ private static function substitutePropertyGenerics(TypeNode $typeNode, object $object, string $className, string $propName = ''): TypeNode + { + return self::substitutePropertyGenericsWithFallback($typeNode, $object, $className, $propName)[0]; + } + + /** + * @return array{0: TypeNode, 1: array{0: int, 1: array}} + */ + private static function substitutePropertyGenericsWithFallback(TypeNode $typeNode, object $object, string $className, string $propName = ''): array { $boundTemplates = TemplateManager::getInstanceBindingsFast($object); + $fallbackKeys = TemplateManager::getFallbackBoundTemplates($object); if ($propName !== '') { self::$instancePropertyTypeCache ??= new \WeakMap(); $entry = self::$instancePropertyTypeCache[$object] ?? null; - if ($entry !== null && $entry['bindings'] === $boundTemplates && isset($entry['props'][$propName])) { - return $entry['props'][$propName]; + if ($entry !== null && $entry['bindings'] === $boundTemplates && $entry['fallbackKeys'] === $fallbackKeys && isset($entry['props'][$propName])) { + return [$entry['props'][$propName], $entry['fallbacks'][$propName] ?? [0, []]]; } } @@ -833,7 +887,12 @@ private static function substitutePropertyGenerics(TypeNode $typeNode, object $o $allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; } + $fallbackMeta = [0, []]; if ($boundTemplates !== [] || $allTemplates !== []) { + $concreteBindings = $fallbackKeys !== [] + ? array_diff_key($boundTemplates, $fallbackKeys) + : $boundTemplates; + $fallbackMeta = TemplateManager::collectUnboundGenericArgIndices($typeNode, $concreteBindings, $allTemplates); $subNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $allTemplates); if ($subNode !== $typeNode && (class_exists($className, false) || interface_exists($className, false) || trait_exists($className, false) || class_exists($className))) { @@ -852,18 +911,21 @@ private static function substitutePropertyGenerics(TypeNode $typeNode, object $o if ($propName !== '') { self::$instancePropertyTypeCache ??= new \WeakMap(); $entry = self::$instancePropertyTypeCache[$object] ?? null; - if ($entry === null || $entry['bindings'] !== $boundTemplates) { + if ($entry === null || $entry['bindings'] !== $boundTemplates || $entry['fallbackKeys'] !== $fallbackKeys) { self::$instancePropertyTypeCache[$object] = [ 'bindings' => $boundTemplates, + 'fallbackKeys' => $fallbackKeys, 'props' => [$propName => $typeNode], + 'fallbacks' => [$propName => $fallbackMeta], ]; } else { $entry['props'][$propName] = $typeNode; + $entry['fallbacks'][$propName] = $fallbackMeta; self::$instancePropertyTypeCache[$object] = $entry; } } - return $typeNode; + return [$typeNode, $fallbackMeta]; } /** diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index a7a66124..3742dc08 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -166,6 +166,11 @@ final class ParamChecker */ private static array $substitutedParamCache = []; + /** + * @var array}>> + */ + private static array $substitutedParamFallbackCache = []; + private static ?IdentifierTypeNode $arrayKeyNode = null; private static ?UnionTypeNode $intOrStringUnionNode = null; @@ -185,6 +190,7 @@ public static function reset(): void { self::$preInferMaskCache = []; self::$substitutedParamCache = []; + self::$substitutedParamFallbackCache = []; self::$effectiveFunctionCache = []; self::$noParamContractCache = []; self::$functionKindCache = []; @@ -2121,11 +2127,15 @@ private static function inferGenericObjectNode( if (! TemplateManager::isBound($effectiveFunction, $targetObj, $tName)) { $targetTemplateName = $targetTemplateNames[$idx] ?? null; $inferredCandidate = null; + $sourceTemplateName = null; if ($targetTemplateName !== null && isset($boundOnInstance[$targetTemplateName])) { $inferredCandidate = $boundOnInstance[$targetTemplateName]; + $sourceTemplateName = $targetTemplateName; } elseif (isset($instanceBoundTypes[$idx])) { $inferredCandidate = $instanceBoundTypes[$idx]; + $boundKeys = array_keys($boundOnInstance); + $sourceTemplateName = $boundKeys[$idx] ?? null; } if ($inferredCandidate !== null) { @@ -2139,6 +2149,9 @@ private static function inferGenericObjectNode( if ($satisfiesBound) { TemplateManager::bindTemplate($effectiveFunction, $targetObj, $tName, $inferredCandidate); + if ($targetObj !== null && $sourceTemplateName !== null && TemplateManager::isFallbackBound($value, $sourceTemplateName)) { + TemplateManager::markFallbackBound($targetObj, $tName); + } } } } @@ -2463,6 +2476,9 @@ private static function validateSingleParam( $isBareTemplate = self::getTemplateName($typeNode, $templates) !== null; $shouldSkipTemplateSub = $isBareTemplate || $isClassStringT; + $thisFallbackKeys = $thisObj !== null ? TemplateManager::getFallbackBoundTemplates($thisObj) : []; + + $fallbackMeta = [0, []]; if (! $shouldSkipTemplateSub && (\count($boundTemplates) > 0 || \count($declaredTemplates) > 0)) { $boundCount = \count($boundTemplates); $sig = null; @@ -2485,12 +2501,19 @@ private static function validateSingleParam( if (str_contains($sig, 'static') || str_contains($sig, '$this')) { $sig = null; + } elseif ($thisFallbackKeys !== []) { + $sig .= '!fb:' . implode(',', array_keys($thisFallbackKeys)); } } if ($sig !== null && isset(self::$substitutedParamCache[$cacheKey][$sig])) { $typeNode = self::$substitutedParamCache[$cacheKey][$sig]; + $fallbackMeta = self::$substitutedParamFallbackCache[$cacheKey][$sig] ?? [0, []]; } else { + $concreteBound = $thisFallbackKeys !== [] + ? array_diff_key($boundTemplates, $thisFallbackKeys) + : $boundTemplates; + $fallbackMeta = TemplateManager::collectUnboundGenericArgIndices($typeNode, $concreteBound, $declaredTemplates); $subType = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $declaredTemplates); if ($subType !== $typeNode) { $typeNode = SpecialTypeResolver::resolve($subType, $effectiveFunction, $thisObj); @@ -2498,6 +2521,7 @@ private static function validateSingleParam( if ($sig !== null && $cacheKey !== null) { self::$substitutedParamCache[$cacheKey][$sig] = $typeNode; + self::$substitutedParamFallbackCache[$cacheKey][$sig] = $fallbackMeta; } } } @@ -2514,7 +2538,21 @@ private static function validateSingleParam( return self::resolveTemplateParam($typeNode, $val, $paramName, $effectiveFunction, $thisObj, $templates, $registry, $classTemplates, $thisOrClass); } - return $registry->validate($val, $typeNode, $effectiveFunction . '(): Argument $' . $paramName, $isSensitive); + $preExistingBindings = null; + if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($val) && $typeNode instanceof GenericTypeNode) { + $preExistingBindings = TemplateManager::$instanceTemplateBindings[$val] ?? []; + } + + $err = $registry->validate($val, $typeNode, $effectiveFunction . '(): Argument $' . $paramName, $isSensitive); + if ($err !== null) { + return $err; + } + + if ($preExistingBindings !== null && \is_object($val) && $typeNode instanceof GenericTypeNode) { + TemplateManager::markFallbackReturnBindings($val, $typeNode, $fallbackMeta[1], $fallbackMeta[0], $preExistingBindings); + } + + return null; } /** diff --git a/src/Internal/Checker/ParamOutChecker.php b/src/Internal/Checker/ParamOutChecker.php index ff23c28d..5938a6d8 100644 --- a/src/Internal/Checker/ParamOutChecker.php +++ b/src/Internal/Checker/ParamOutChecker.php @@ -67,7 +67,7 @@ public static function checkParamOut( return null; } - $paramOuts = $paramOuts = $contract['paramOuts'] ?? []; + $paramOuts = $contract['paramOuts'] ?? []; if (! isset($paramOuts[$paramName])) { return null; diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index a70a6dd0..207a5207 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -71,6 +71,21 @@ final class ReturnChecker */ public static array $substitutedConditionalReturnCache = []; + /** + * @var array}> + */ + public static array $unboundReturnFallbackCache = []; + + /** + * @var array}>> + */ + public static array $substitutedReturnFallbackCache = []; + + /** + * @var array}>>> + */ + public static array $substitutedCondReturnFallbackCache = []; + /** * Resets internal caches. Useful for test isolation. */ @@ -81,6 +96,9 @@ public static function reset(): void self::$resolvedStaticReturnCache = []; self::$unboundReturnCache = []; self::$substitutedReturnCache = []; + self::$unboundReturnFallbackCache = []; + self::$substitutedReturnFallbackCache = []; + self::$substitutedCondReturnFallbackCache = []; } /** @@ -417,6 +435,8 @@ private static function evaluateReturn( $sig = null; $cacheFunc = null; $boundCount = \count($boundTemplates); + $fallbackMeta = [0, []]; + $thisFallbackKeys = $thisObj !== null ? TemplateManager::getFallbackBoundTemplates($thisObj) : []; if ($boundCount <= 5 && ($thisObj !== null || ! $isDynamicReturn)) { $cacheFunc = ($isDynamicReturn && $thisObj !== null) ? ($function . '@' . $thisObj::class) : $function; @@ -436,8 +456,14 @@ private static function evaluateReturn( if (str_contains($sig, 'static') || str_contains($sig, '$this')) { $sig = null; - } elseif (! $hasConditionals && isset(self::$substitutedReturnCache[$cacheFunc][$sig])) { - $resolvedType = self::$substitutedReturnCache[$cacheFunc][$sig]; + } else { + if ($thisFallbackKeys !== []) { + $sig .= '!fb:' . implode(',', array_keys($thisFallbackKeys)); + } + if (! $hasConditionals && isset(self::$substitutedReturnCache[$cacheFunc][$sig])) { + $resolvedType = self::$substitutedReturnCache[$cacheFunc][$sig]; + $fallbackMeta = self::$substitutedReturnFallbackCache[$cacheFunc][$sig] ?? [0, []]; + } } } @@ -460,18 +486,30 @@ private static function evaluateReturn( $condBranchKey = (string) $resolvedType; if (isset(self::$substitutedConditionalReturnCache[$cacheFunc][$condBranchKey][$sig])) { $resolvedType = self::$substitutedConditionalReturnCache[$cacheFunc][$condBranchKey][$sig]; + $fallbackMeta = self::$substitutedCondReturnFallbackCache[$cacheFunc][$condBranchKey][$sig] ?? [0, []]; $condCacheHit = true; } } if (! $condCacheHit) { if ($boundCount === 0 && \count($templates) > 0 && ! $hasConditionals && $thisObj === null) { - $resolvedType = self::$unboundReturnCache[$function] ??= SpecialTypeResolver::resolve( - TemplateSubstitutor::substitute($returnTypeNode, [], $templates), - $function, - null - ); + if (isset(self::$unboundReturnCache[$function])) { + $resolvedType = self::$unboundReturnCache[$function]; + $fallbackMeta = self::$unboundReturnFallbackCache[$function] ?? [0, []]; + } else { + $fallbackMeta = self::collectUnboundReturnArgIndices($resolvedType, [], $templates); + self::$unboundReturnFallbackCache[$function] = $fallbackMeta; + $resolvedType = self::$unboundReturnCache[$function] = SpecialTypeResolver::resolve( + TemplateSubstitutor::substitute($resolvedType, [], $templates), + $function, + null + ); + } } elseif ($boundCount > 0 || \count($templates) > 0) { + $concreteBound = $thisFallbackKeys !== [] + ? array_diff_key($boundTemplates, $thisFallbackKeys) + : $boundTemplates; + $fallbackMeta = self::collectUnboundReturnArgIndices($resolvedType, $concreteBound, $templates); $subType = TemplateSubstitutor::substitute($resolvedType, $boundTemplates, $templates); $resolvedType = $isDynamicReturn ? SpecialTypeResolver::resolve($subType, $function, $thisObj) @@ -485,8 +523,10 @@ private static function evaluateReturn( if ($sig !== null && $cacheFunc !== null) { if ($hasConditionals && $condBranchKey !== null) { self::$substitutedConditionalReturnCache[$cacheFunc][$condBranchKey][$sig] = $resolvedType; + self::$substitutedCondReturnFallbackCache[$cacheFunc][$condBranchKey][$sig] = $fallbackMeta; } elseif (! $hasConditionals) { self::$substitutedReturnCache[$cacheFunc][$sig] = $resolvedType; + self::$substitutedReturnFallbackCache[$cacheFunc][$sig] = $fallbackMeta; } } } @@ -499,11 +539,20 @@ private static function evaluateReturn( } } + $preExistingBindings = null; + if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $resolvedType instanceof GenericTypeNode) { + $preExistingBindings = TemplateManager::$instanceTemplateBindings[$value] ?? []; + } + $err = $registry->validate($value, $resolvedType, 'Return value'); if ($err !== null) { return ErrorFactory::createError($function . '(): ' . $err->getMessage()); } + if ($preExistingBindings !== null && \is_object($value) && $resolvedType instanceof GenericTypeNode) { + TemplateManager::markFallbackReturnBindings($value, $resolvedType, $fallbackMeta[1], $fallbackMeta[0], $preExistingBindings); + } + if ($resolvedType instanceof CallableTypeNode && CallableWrapper::isCallable($value)) { return CallableWrapper::wrapTypeNode($resolvedType, $value, $function . '(): Return value', $registry); } @@ -523,4 +572,18 @@ private static function evaluateReturn( return $value; } + + /** + * @param array $boundTemplates + * @param array $declaredTemplates + * + * @return array{0: int, 1: array} + */ + private static function collectUnboundReturnArgIndices( + TypeNode $preSubNode, + array $boundTemplates, + array $declaredTemplates + ): array { + return TemplateManager::collectUnboundGenericArgIndices($preSubNode, $boundTemplates, $declaredTemplates); + } } diff --git a/src/Internal/Docblock/DocblockNormalizer.php b/src/Internal/Docblock/DocblockNormalizer.php index 232639c4..fb72875b 100644 --- a/src/Internal/Docblock/DocblockNormalizer.php +++ b/src/Internal/Docblock/DocblockNormalizer.php @@ -32,54 +32,58 @@ final class DocblockNormalizer */ public static function normalize(string $doc): string { - if (! str_contains($doc, '@')) { + $hasAt = str_contains($doc, '@'); + + if (! $hasAt && str_starts_with(ltrim($doc), '/**')) { return $doc; } - if (str_contains($doc, "\n")) { - $doc = preg_replace( - '/(@(?:phpstan-|psalm-)?(?:param-out|param|return|var|self-out|this-out|throws))[ \t]*\r?\n[ \t]*\*[ \t]+(?![@*\/])/m', - '$1 ', - $doc - ) ?? $doc; - } + if ($hasAt) { + if (str_contains($doc, "\n")) { + $doc = preg_replace( + '/(@(?:phpstan-|psalm-)?(?:param-out|param|return|var|self-out|this-out|throws))[ \t]*\r?\n[ \t]*\*[ \t]+(?![@*\/])/m', + '$1 ', + $doc + ) ?? $doc; + } - if (substr_count($doc, '@') > 1) { - $doc = preg_replace_callback( - '/(?:\/\*\*|^\s*\*)\s*@[a-zA-Z0-9_-]+[^\r\n]*/m', - static function (array $matches): string { - return preg_replace( - '/([^\r\n*\/ \t])[ \t]+(@(?:phpstan-|psalm-|template-)?(?:param-out|param|return|var|template(?:-covariant|-contravariant)?|self-out|this-out|type|import-type|extends|implements|use|property(?:-read|-write)?|method)\b)/', - "$1\n * $2", - $matches[0] - ) ?? $matches[0]; - }, - $doc - ) ?? $doc; - } + if (substr_count($doc, '@') > 1) { + $doc = preg_replace_callback( + '/(?:\/\*\*|^\s*\*)\s*@[a-zA-Z0-9_-]+[^\r\n]*/m', + static function (array $matches): string { + return preg_replace( + '/([^\r\n*\/ \t])[ \t]+(@(?:phpstan-|psalm-|template-)?(?:param-out|param|return|var|template(?:-covariant|-contravariant)?|self-out|this-out|type|import-type|extends|implements|use|property(?:-read|-write)?|method)\b)/', + "$1\n * $2", + $matches[0] + ) ?? $matches[0]; + }, + $doc + ) ?? $doc; + } - if (str_contains($doc, 'param-out') && str_contains($doc, '&')) { - $doc = preg_replace( - '/(@(?:phpstan-|psalm-)?param-out\s+[^\r\n]+?)\s*&\s*(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)(?=\s|$|\*\/)/', - '$1 $2', - $doc - ) ?? $doc; - } + if (str_contains($doc, 'param-out') && str_contains($doc, '&')) { + $doc = preg_replace( + '/(@(?:phpstan-|psalm-)?param-out\s+[^\r\n]+?)\s*&\s*(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)(?=\s|$|\*\/)/', + '$1 $2', + $doc + ) ?? $doc; + } - if (str_contains($doc, '-type') && str_contains($doc, '=')) { - $doc = preg_replace('/(@(?:phpstan|psalm)-type\s+[a-zA-Z0-9_\x80-\xff]+)\s*=\s*/', '$1 ', $doc) ?? $doc; - } + if (str_contains($doc, '-type') && str_contains($doc, '=')) { + $doc = preg_replace('/(@(?:phpstan|psalm)-type\s+[a-zA-Z0-9_\x80-\xff]+)\s*=\s*/', '$1 ', $doc) ?? $doc; + } - if (stripos($doc, 'static') !== false && stripos($doc, 'closure') !== false) { - $doc = preg_replace('/(?:\(\s*static\s+Closure\s*\)|static\s+Closure\b)/i', 'static-closure', $doc) ?? $doc; - } + if (str_contains($doc, '@self-out') && ! str_contains($doc, '@phpstan-self-out') && ! str_contains($doc, '@psalm-self-out')) { + $doc = preg_replace('/@self-out\b/', '@phpstan-self-out', $doc) ?? $doc; + } - if (str_contains($doc, '@self-out') && ! str_contains($doc, '@phpstan-self-out') && ! str_contains($doc, '@psalm-self-out')) { - $doc = preg_replace('/@self-out\b/', '@phpstan-self-out', $doc) ?? $doc; + if (str_contains($doc, '@this-out') && ! str_contains($doc, '@phpstan-this-out') && ! str_contains($doc, '@psalm-this-out')) { + $doc = preg_replace('/@this-out\b/', '@phpstan-this-out', $doc) ?? $doc; + } } - if (str_contains($doc, '@this-out') && ! str_contains($doc, '@phpstan-this-out') && ! str_contains($doc, '@psalm-this-out')) { - $doc = preg_replace('/@this-out\b/', '@phpstan-this-out', $doc) ?? $doc; + if (stripos($doc, 'static') !== false && stripos($doc, 'closure') !== false) { + $doc = preg_replace('/(?:\(\s*static\s+Closure\s*\)|static\s+Closure\b)/i', 'static-closure', $doc) ?? $doc; } if (stripos($doc, 'callable') !== false || stripos($doc, 'closure') !== false) { @@ -107,7 +111,7 @@ static function (array $matches): string { ) ?? $doc; } - if (str_contains($doc, '$')) { + if ($hasAt && str_contains($doc, '$')) { $doc = preg_replace('/([ \t]*\*[ \t]*(?:\|[^\r\n]+|\@[a-zA-Z\-]+[^\r\n]+))[ \t]*\r?\n[ \t]*\*[ \t]*(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)\b/', '$1 $2', $doc) ?? $doc; } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 4970d43f..e29343fd 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -51,6 +51,14 @@ final class TemplateManager */ public static ?WeakMap $instanceTemplateBindings = null; + /** + * Tracks template names per instance whose current binding came from an implicit default/bound fallback + * rather than an explicit specialization or concrete argument inference. + * + * @var WeakMap>|null + */ + private static ?WeakMap $fallbackBoundTemplates = null; + /** * Call stack frames storing template bindings per function or method call. * @@ -417,7 +425,7 @@ final class TemplateManager /** * Stack storing pending generic instantiations for constructors. * - * @var list + * @var list */ private static array $pendingInstantiations = []; @@ -671,6 +679,7 @@ public static function reset(): void self::$verifiedShallowRefinements = null; self::$compiledBindPlanBySigCache = []; self::$propagatedPropTypeCache = []; + self::$fallbackBoundTemplates = null; } /** @@ -689,6 +698,118 @@ public static function restoreInstanceBindings(object $instance, array $bindings } } + public static function isFallbackBound(object $instance, string $templateName): bool + { + return self::$fallbackBoundTemplates !== null && isset(self::$fallbackBoundTemplates[$instance][$templateName]); + } + + public static function markFallbackBound(object $instance, string $templateName): void + { + self::$fallbackBoundTemplates ??= new WeakMap(); + $map = self::$fallbackBoundTemplates[$instance] ?? []; + $map[$templateName] = true; + self::$fallbackBoundTemplates[$instance] = $map; + } + + public static function clearFallbackBound(object $instance, string $templateName): void + { + if (self::$fallbackBoundTemplates !== null && isset(self::$fallbackBoundTemplates[$instance][$templateName])) { + $map = self::$fallbackBoundTemplates[$instance]; + unset($map[$templateName]); + if ($map === []) { + unset(self::$fallbackBoundTemplates[$instance]); + } else { + self::$fallbackBoundTemplates[$instance] = $map; + } + } + } + + /** + * Returns template names on an instance whose bindings came from unbound template fallbacks. + * + * @return array + */ + public static function getFallbackBoundTemplates(object $instance): array + { + return self::$fallbackBoundTemplates !== null + ? (self::$fallbackBoundTemplates[$instance] ?? []) + : []; + } + + /** + * Marks newly bound template slots on an instance as fallback-derived when populated from + * unbound template parameters in a return contract. + * + * @param array $fallbackArgIndices + * @param array $preExistingBindings + */ + public static function markFallbackReturnBindings( + object $instance, + GenericTypeNode $returnNode, + array $fallbackArgIndices, + int $preSubArgCount, + array $preExistingBindings + ): void { + if ($preSubArgCount !== -1 && $fallbackArgIndices === []) { + return; + } + + try { + $targetClass = (string) $returnNode->type; + $lookupClass = ( + ! isset(self::CONTEXT_SELF_REFERENCES[strtolower($targetClass)]) + && ClassNameValidator::isValid($targetClass) + && self::isRealTypeSymbol($targetClass) + ) ? $targetClass : $instance::class; + + [$templates] = self::hierarchyTemplatesForClass($lookupClass); + if ($templates === []) { + return; + } + + $templateList = array_values($templates); + $templateCount = \count($templateList); + + if ($preSubArgCount === -1) { + foreach ($templateList as $idx => $templateTag) { + if (isset($returnNode->genericTypes[$idx]) && ! isset($preExistingBindings[$templateTag->name])) { + self::markFallbackBound($instance, $templateTag->name); + } + } + + return; + } + + if ($preSubArgCount === 1 && $templateCount === 2) { + $firstTemplate = $templateList[0]; + $firstBound = $firstTemplate->bound !== null ? strtolower((string) $firstTemplate->bound) : ''; + $firstName = strtolower($firstTemplate->name); + $isKeyTemplate = $firstBound === 'array-key' || isset(self::KEY_TEMPLATE_NAMES[$firstName]); + + if ($isKeyTemplate) { + if (! isset($preExistingBindings[$firstTemplate->name])) { + self::markFallbackBound($instance, $firstTemplate->name); + } + if (isset($fallbackArgIndices[0]) && ! isset($preExistingBindings[$templateList[1]->name])) { + self::markFallbackBound($instance, $templateList[1]->name); + } + + return; + } + } + + foreach ($fallbackArgIndices as $idx => $_) { + if (isset($templateList[$idx])) { + $tName = $templateList[$idx]->name; + if (! isset($preExistingBindings[$tName])) { + self::markFallbackBound($instance, $tName); + } + } + } + } catch (\Throwable) { + } + } + /** * Pushes a pre-bound single-template call frame onto the stack in O(1). */ @@ -730,6 +851,7 @@ public static function pushPendingInstantiation(string $typeString, string $file 'typeString' => $resolvedTypeString, 'file' => $file, 'targetClass' => $targetClass, + 'consumed' => false, ]; self::$hasPendingInstantiations = true; } @@ -752,12 +874,81 @@ public static function applyPendingInstantiation(object $instance): void return; } - $pending = end(self::$pendingInstantiations); - if ($pending !== false && $pending['targetClass'] !== '' && is_a($instance, $pending['targetClass'])) { + $lastIdx = \count(self::$pendingInstantiations) - 1; + if ($lastIdx < 0) { + return; + } + + $pending = self::$pendingInstantiations[$lastIdx]; + if ($pending['targetClass'] !== '' && is_a($instance, $pending['targetClass'])) { + self::$pendingInstantiations[$lastIdx]['consumed'] = true; + self::bindInstance($instance, $pending['typeString'], $pending['file']); + } + } + + public static function applyPendingInstantiationIfUnconsumed(object $instance): void + { + if (! self::$hasPendingInstantiations || ! Config::isInlineGenericsEnabled()) { + return; + } + + $lastIdx = \count(self::$pendingInstantiations) - 1; + if ($lastIdx < 0) { + return; + } + + $pending = self::$pendingInstantiations[$lastIdx]; + if (! $pending['consumed'] && $pending['targetClass'] !== '' && is_a($instance, $pending['targetClass'])) { + self::$pendingInstantiations[$lastIdx]['consumed'] = true; self::bindInstance($instance, $pending['typeString'], $pending['file']); } } + /** + * Identifies generic argument positions that reference unbound templates and will fall back + * to their declared default or upper bound during TemplateSubstitutor::substitute(). + * + * @param array $boundTemplates + * @param array $declaredTemplates + * + * @return array{0: int, 1: array} + */ + public static function collectUnboundGenericArgIndices( + TypeNode $preSubNode, + array $boundTemplates, + array $declaredTemplates + ): array { + if ($declaredTemplates === []) { + return [0, []]; + } + + if ($preSubNode instanceof IdentifierTypeNode && isset($declaredTemplates[$preSubNode->name]) && ! isset($boundTemplates[$preSubNode->name])) { + return [-1, []]; + } + + if (! ($preSubNode instanceof GenericTypeNode)) { + return [0, []]; + } + + $unboundTemplates = $boundTemplates === [] + ? $declaredTemplates + : array_diff_key($declaredTemplates, $boundTemplates); + + if ($unboundTemplates === []) { + return [\count($preSubNode->genericTypes), []]; + } + + /** @var array $indices */ + $indices = []; + foreach ($preSubNode->genericTypes as $idx => $gt) { + if (DocblockParser::typeReferencesTemplate($gt, $unboundTemplates)) { + $indices[(int) $idx] = true; + } + } + + return [\count($preSubNode->genericTypes), $indices]; + } + /** * Returns template names explicitly declared on the class itself. * @@ -873,9 +1064,21 @@ public static function isGeneratorInferred(object $instance): bool public static function copyInstanceBindings(object $source, object $target): void { if (self::$instanceTemplateBindings !== null && isset(self::$instanceTemplateBindings[$source])) { - $bindings = self::$instanceTemplateBindings[$source]; - $bindings = self::widenClonedBindingsFromActiveCall($target, $bindings); + $sourceBindings = self::$instanceTemplateBindings[$source]; + $bindings = self::widenClonedBindingsFromActiveCall($target, $sourceBindings); self::$instanceTemplateBindings[$target] = $bindings; + + if (self::$fallbackBoundTemplates !== null && isset(self::$fallbackBoundTemplates[$source])) { + $copiedFallbacks = []; + foreach (self::$fallbackBoundTemplates[$source] as $tName => $_) { + if (isset($bindings[$tName]) && $bindings[$tName] === ($sourceBindings[$tName] ?? null)) { + $copiedFallbacks[$tName] = true; + } + } + if ($copiedFallbacks !== []) { + self::$fallbackBoundTemplates[$target] = $copiedFallbacks; + } + } } if (self::isGeneratorInferred($source)) { @@ -1301,6 +1504,7 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ } self::$instanceTemplateBindings[$thisObj] = $bindings; + self::clearFallbackBound($thisObj, $templateName); } else { if (! isset(self::$topCallFrame[$function])) { self::$topCallFrame[$function] = [$templateName => $inferredType]; @@ -1316,8 +1520,14 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ * Binds generic template types to an object instance or validates variance against an existing binding. * With $refineOnly, an existing binding is never replaced by a less specific one (downward propagation). */ - public static function bindInstanceFromNode(object $instance, GenericTypeNode $typeNode, string $context = '', bool $forceBind = false, bool $refineOnly = false): ?ErrorMessage - { + public static function bindInstanceFromNode( + object $instance, + GenericTypeNode $typeNode, + string $context = '', + bool $forceBind = false, + bool $refineOnly = false, + bool $allowBoundSpecialization = false + ): ?ErrorMessage { self::$compiledNodeBindPlanCache ??= new WeakMap(); $plan = self::$compiledNodeBindPlanCache[$typeNode] ?? null; @@ -1474,7 +1684,8 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t $candidateBindings, $refineOnly, $planItem !== null && $planItem['symbolValid'], - $planItem !== null && $planItem['boundSatisfied'] + $planItem !== null && $planItem['boundSatisfied'], + $allowBoundSpecialization ); if ($err !== null) { return $err; @@ -1685,6 +1896,7 @@ public static function applyClassTemplateDefaults(object $instance, array $class foreach ($classTemplates as $tName => $templateTag) { if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { $bindings[$tName] = $templateTag->default; + self::markFallbackBound($instance, $tName); $changed = true; } } @@ -1871,7 +2083,7 @@ private static function propagateBindingsToInstanceProperties( } if ($resolvedPropType !== null) { - self::bindInstanceFromNode($propVal, $resolvedPropType, forceBind: true, refineOnly: true); + self::bindInstanceFromNode($propVal, $resolvedPropType, forceBind: false, refineOnly: true); } } @@ -2117,7 +2329,8 @@ private static function bindSingleTemplateArgument( array $candidateBindings = [], bool $refineOnly = false, bool $symbolPreVerified = false, - bool $boundPreVerified = false + bool $boundPreVerified = false, + bool $allowBoundSpecialization = false ): ?ErrorMessage { if (! $symbolPreVerified) { if ($expectedTypeNode instanceof IdentifierTypeNode) { @@ -2189,7 +2402,7 @@ private static function bindSingleTemplateArgument( $valid = self::checkVariance($existingTypeNode, $expectedTypeNode, $variance); if (! $valid) { - if ($forceBind || ($isReturnContext && self::isGeneratorInferred($instance))) { + if (($forceBind && ! $refineOnly) || ($isReturnContext && self::isGeneratorInferred($instance))) { $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; @@ -2201,6 +2414,7 @@ private static function bindSingleTemplateArgument( } self::$instanceTemplateBindings[$instance] = $bindings; + self::clearFallbackBound($instance, $templateName); if ($isReturnContext && self::isGeneratorInferred($instance)) { self::propagateGeneratorRefinementToProperties($instance, $templateName, $expectedTypeNode); @@ -2209,15 +2423,29 @@ private static function bindSingleTemplateArgument( return null; } - $isDefaultOrBound = self::isUnspecializedType($existingTypeNode) - || ($templateTag->bound !== null && self::matchesBoundOrDefault($existingTypeNode, $templateTag->bound)) - || ($templateTag->default !== null && self::matchesBoundOrDefault($existingTypeNode, $templateTag->default)); + $allowInheritedUnionBound = $allowBoundSpecialization + && $existingTypeNode instanceof UnionTypeNode + && $templateTag->bound !== null + && self::matchesBoundOrDefault($existingTypeNode, $templateTag->bound); + + $isFallbackOrUnspecialized = self::isUnspecializedType($existingTypeNode) + || self::isFallbackBound($instance, $templateName) + || $allowInheritedUnionBound; if (self::checkVariance($expectedTypeNode, $existingTypeNode, GenericTypeNode::VARIANCE_COVARIANT)) { - if ($isDefaultOrBound || ($isReturnContext && ! $strictInvariance)) { + if ($isFallbackOrUnspecialized || ($isReturnContext && ! $strictInvariance)) { $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; + + $rawMappings = self::$classInheritedRawMappingsCache[$instance::class] ?? []; + foreach ($rawMappings as $tName => $rawNode) { + if (DocblockParser::typeReferencesTemplate($rawNode, [$templateName => true])) { + $bindings[$tName] = TemplateSubstitutor::substitute($rawNode, $bindings); + } + } + self::$instanceTemplateBindings[$instance] = $bindings; + self::clearFallbackBound($instance, $templateName); return null; } @@ -2234,6 +2462,7 @@ private static function bindSingleTemplateArgument( $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; self::$instanceTemplateBindings[$instance] = $bindings; + self::clearFallbackBound($instance, $templateName); return null; } @@ -2256,7 +2485,7 @@ private static function bindSingleTemplateArgument( } } - if ($forceBind || ! isset($existingBindings[$templateName])) { + if (($forceBind && ! $refineOnly) || ! isset($existingBindings[$templateName])) { $map = self::$instanceTemplateBindings ??= new WeakMap(); $bindings = $map[$instance] ?? []; @@ -2264,16 +2493,19 @@ private static function bindSingleTemplateArgument( if ($refineOnly && isset($existingBindings[$templateName])) { $existingTypeNode = $existingBindings[$templateName]; - - $isPlaceholder = self::isUnspecializedArgument($boundNode, $templateTag); $isRefinement = self::checkVariance($boundNode, $existingTypeNode, GenericTypeNode::VARIANCE_COVARIANT); - if ($isPlaceholder && ! $isRefinement) { + if (! $isRefinement) { return null; } } $bindings[$templateName] = $boundNode; + if ($isWildcardOrMixed) { + self::markFallbackBound($instance, $templateName); + } else { + self::clearFallbackBound($instance, $templateName); + } $rawMappings = self::$classInheritedRawMappingsCache[$instance::class] ?? []; foreach ($rawMappings as $tName => $rawNode) { @@ -2362,27 +2594,6 @@ public static function isUnspecializedType(TypeNode $node): bool return false; } - /** - * Checks if a generic type argument carries no information: an unspecialized placeholder, - * or nothing beyond the template's own declared bound or default. - */ - private static function isUnspecializedArgument(TypeNode $node, TemplateTagValueNode $templateTag): bool - { - if (self::isUnspecializedType($node)) { - return true; - } - - if ($templateTag->bound !== null && self::matchesBoundOrDefault($node, $templateTag->bound)) { - return true; - } - - if ($templateTag->default !== null && self::matchesBoundOrDefault($node, $templateTag->default)) { - return true; - } - - return false; - } - /** * Recursively verifies variance across array shape elements. */ @@ -3487,11 +3698,11 @@ public static function bindInstance(object $instance, string $typeString, string } if ($typeNode instanceof GenericTypeNode) { - self::bindInstanceFromNode($instance, $typeNode, '', true); + self::bindInstanceFromNode($instance, $typeNode, '', false, false, true); } elseif ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) { $matching = self::collectMatchingObjectGenericNodes($instance, $typeNode); if (\count($matching) === 1) { - self::bindInstanceFromNode($instance, $matching[0], '', true); + self::bindInstanceFromNode($instance, $matching[0], '', false, false, true); } } } catch (\Throwable $e) { diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index 41ca63a4..369fc401 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -25,7 +25,6 @@ final class CacheManager private const RUNTIME_ONLY_CONFIG_KEYS = [ 'enabled' => true, 'auto_boot' => true, - 'on_violation' => true, 'report_file' => true, 'fail_on_report' => true, 'fail_on_zero_files' => true, @@ -130,13 +129,17 @@ private static function getTransformFingerprint(): string } $config = array_diff_key(Config::get(), self::RUNTIME_ONLY_CONFIG_KEYS); + // Normalized via effective getters below so env overrides are reflected + // and config-vs-env toggles share the same cache key. + unset($config['on_violation'], $config['eliminate_statically_proven_checks']); ksort($config); return self::$transformFingerprint = hash( 'xxh128', var_export($config, true) - // Env override, so the config array alone does not reflect the effective value. . (Config::isEliminateStaticallyProvenChecksEnabled() ? '1' : '0') + // FunctionContractInjector::collectTrustedParamTypes() only trusts params in 'throw' mode. + . (Config::getOnViolation() === 'throw' ? '1' : '0') . (Config::isCacheCheckMtimeEnabled() ? StubManager::getFilesFingerprint() : '') ); } diff --git a/src/Internal/Io/StreamWrapper.php b/src/Internal/Io/StreamWrapper.php index 9ca725f2..8d8478c3 100644 --- a/src/Internal/Io/StreamWrapper.php +++ b/src/Internal/Io/StreamWrapper.php @@ -49,6 +49,14 @@ final class StreamWrapper implements StreamWrapperInterface private bool $eof = false; + private ?string $openedRawPath = null; + + private ?string $openedNormalizedPath = null; + + private ?string $openedResolvedPath = null; + + private bool $wasWritten = false; + private static bool $isRegistered = false; private static bool $cacheEnabled = true; @@ -380,16 +388,18 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ $isInclude = ($options & self::STREAM_OPEN_FOR_INCLUDE) !== 0; if (! $isInclude || ($mode !== 'r' && $mode !== 'rb' && $mode !== 'rt') || ! Config::isEnabled()) { - return $this->openDirectHandle($path, $mode, $options); + return $this->openDirectHandle($path, $mode, $options, $openedPath); } - if (isset(self::$bypassedPathCache[$path])) { - return $this->openDirectHandle($path, $mode, $options); + $useIncludePath = ($options & STREAM_USE_PATH) !== 0; + + if (! $useIncludePath && isset(self::$bypassedPathCache[$path])) { + return $this->openDirectHandle($path, $mode, $options, $openedPath); } $isPhp = str_ends_with($path, '.php') || str_ends_with(strtolower($path), '.php'); if (! $isPhp) { - return $this->openDirectHandle($path, $mode, $options); + return $this->openDirectHandle($path, $mode, $options, $openedPath); } if ( @@ -401,29 +411,47 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ || str_contains($path, '/cache/views/') || str_contains($path, '/framework/views/') ) { - self::$bypassedPathCache[$path] = true; + if (! $useIncludePath) { + self::$bypassedPathCache[$path] = true; + } - return $this->openDirectHandle($path, $mode, $options); + return $this->openDirectHandle($path, $mode, $options, $openedPath); } $normalizedRaw = str_replace('\\', '/', $path); if (! PathMatcher::mayPathBeIncluded($normalizedRaw)) { - return $this->openDirectHandle($path, $mode, $options); + return $this->openDirectHandle($path, $mode, $options, $openedPath); } self::unregister(); - if (isset(self::$realpathCache[$path])) { + if (! $useIncludePath && isset(self::$realpathCache[$path])) { $resolvedPath = self::$realpathCache[$path]; } else { - $resolvedPath = self::silent(static fn () => realpath($path)); - if ($resolvedPath !== false) { + $resolvedPath = self::silent(static function () use ($path, $useIncludePath): string|false { + $real = realpath($path); + if ($real !== false) { + return $real; + } + + if ($useIncludePath) { + $resolved = stream_resolve_include_path($path); + if ($resolved !== false) { + $realResolved = realpath($resolved); + + return $realResolved !== false ? $realResolved : $resolved; + } + } + + return false; + }); + if (! $useIncludePath && $resolvedPath !== false) { self::$realpathCache[$path] = $resolvedPath; } } if ($resolvedPath === false || ! self::isApplicationFile($path, $resolvedPath)) { - if ($resolvedPath !== false) { + if (! $useIncludePath && $resolvedPath !== false) { self::$bypassedPathCache[$path] = true; } @@ -431,11 +459,21 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ /** @var resource|false $handle */ $handle = self::silent( fn () => ($this->context !== null) - ? fopen($target, $mode, false, $this->context) - : fopen($target, $mode) + ? fopen($target, $mode, $useIncludePath, $this->context) + : fopen($target, $mode, $useIncludePath) ); $this->handle = $handle !== false ? $handle : null; $this->eof = false; + if ($this->handle !== null) { + if ($resolvedPath !== false) { + $openedPath = $resolvedPath; + } else { + $meta = stream_get_meta_data($this->handle); + if (isset($meta['uri']) && $meta['uri'] !== '') { + $openedPath = $meta['uri']; + } + } + } self::register(); if ($this->handle === null && ! self::isPharCall()) { @@ -449,8 +487,11 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ ? $this->openCachedStream($resolvedPath, $mode) : $this->openMemoryStream($resolvedPath); - if ($success && self::shouldTrackTelemetry()) { - self::$instrumentedFiles[$resolvedPath] = true; + if ($success) { + $openedPath = $resolvedPath; + if (self::shouldTrackTelemetry()) { + self::$instrumentedFiles[$resolvedPath] = true; + } } self::register(); @@ -478,10 +519,11 @@ private static function isPharCall(): bool /** * Opens an underlying filesystem handle directly with error reporting options and context support. */ - private function openDirectHandle(string $targetFile, string $mode, int $options): bool + private function openDirectHandle(string $targetFile, string $mode, int $options, ?string &$openedPath = null): bool { $isInclude = ($options & self::STREAM_OPEN_FOR_INCLUDE) !== 0; $useIncludePath = ($options & STREAM_USE_PATH) !== 0; + $isWriteMode = strpbrk($mode, 'waxc+') !== false; self::unregister(); /** @var resource|false $handle */ @@ -492,6 +534,24 @@ private function openDirectHandle(string $targetFile, string $mode, int $options ); $this->handle = $handle !== false ? $handle : null; $this->eof = false; + + if ($this->handle !== null) { + if ($useIncludePath || $isInclude) { + $meta = stream_get_meta_data($this->handle); + if (isset($meta['uri']) && $meta['uri'] !== '') { + $openedPath = $meta['uri']; + } + } + + if ($isWriteMode) { + $this->openedRawPath = $targetFile; + $this->openedNormalizedPath = str_replace('\\', '/', $targetFile); + $resolvedWrite = self::silent(static fn () => realpath($targetFile)); + $this->openedResolvedPath = ($resolvedWrite !== false && $resolvedWrite !== $targetFile) ? $resolvedWrite : null; + $this->wasWritten = true; + $this->invalidateOpenedWritePaths(); + } + } self::register(); if ($this->handle === null && ! self::isPharCall()) { @@ -529,6 +589,11 @@ public function stream_write(string $data): int $res = fwrite($this->handle, $data); + if ($res !== false && $this->openedRawPath !== null) { + $this->wasWritten = true; + $this->invalidateOpenedWritePaths(); + } + return $res !== false ? $res : 0; } @@ -572,7 +637,14 @@ public function stream_truncate(int $new_size): bool return false; } - return ftruncate($this->handle, $new_size); + $res = ftruncate($this->handle, $new_size); + + if ($res && $this->openedRawPath !== null) { + $this->wasWritten = true; + $this->invalidateOpenedWritePaths(); + } + + return $res; } public function stream_eof(): bool @@ -632,6 +704,38 @@ public function stream_close(): void $this->handle = null; $this->eof = false; } + + if ($this->wasWritten) { + $this->invalidateOpenedWritePaths(); + } + + $this->openedRawPath = null; + $this->openedNormalizedPath = null; + $this->openedResolvedPath = null; + $this->wasWritten = false; + } + + private function invalidateOpenedWritePaths(): void + { + if ($this->openedRawPath !== null) { + self::invalidatePathCache($this->openedRawPath, $this->openedNormalizedPath); + } + + if ($this->openedResolvedPath !== null) { + self::invalidatePathCache($this->openedResolvedPath); + } + } + + private static function invalidatePathCache(string $path, ?string $normalized = null): void + { + $norm = $normalized ?? str_replace('\\', '/', $path); + unset( + self::$statCache[$norm . ':stat'], + self::$statCache[$norm . ':lstat'], + self::$staticNegativeStatCache[$norm], + self::$realpathCache[$path], + self::$bypassedPathCache[$path] + ); } /** diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 3ac9fc35..c586bdb6 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -118,7 +118,7 @@ final class RuntimeTypeChecker private static ?TypeValidatorRegistry $registry = null; /** - * @var array}> + * @var array}> */ private static array $simpleScopePlanCache = []; @@ -150,7 +150,7 @@ final class RuntimeTypeChecker private static array $genericReturnPlanCache = []; /** - * @var array}>> + * @var array}>> */ private static array $traitScopePlanCache = []; @@ -789,7 +789,12 @@ public static function withPendingGeneric(string $typeString, \Closure $factory, TemplateManager::pushPendingInstantiation($typeString, $file); try { - return $factory(...$args); + $result = $factory(...$args); + if (\is_object($result)) { + TemplateManager::applyPendingInstantiationIfUnconsumed($result); + } + + return $result; } finally { TemplateManager::popPendingInstantiation(); } @@ -1944,7 +1949,7 @@ private static function compilePrimitiveBoundMask(TypeNode $node): int } /** - * @param array{class: ?string, requireObject: bool, function: string, items: list} $plan + * @param array{class: ?string, requireObject: bool, function: string, items: list} $plan * @param array $vars */ private static function executeSimpleScopePlan(array $plan, array $vars): ?ErrorMessage @@ -1953,7 +1958,6 @@ private static function executeSimpleScopePlan(array $plan, array $vars): ?Error return null; } - $registry = self::$registry ??= new TypeValidatorRegistry(); $effectiveFunc = $plan['function']; foreach ($plan['items'] as $item) { @@ -1962,6 +1966,9 @@ private static function executeSimpleScopePlan(array $plan, array $vars): ?Error if (isset($vars[$paramName])) { $val = $vars[$paramName]; } elseif (\array_key_exists($paramName, $vars)) { + if ($item[5]) { + continue; + } $val = null; } else { continue; @@ -1974,6 +1981,8 @@ private static function executeSimpleScopePlan(array $plan, array $vars): ?Error self::PARAM_CHECK_STRING => \is_string($val), self::PARAM_CHECK_BOOL => \is_bool($val), self::PARAM_CHECK_FLOAT => \is_float($val) || \is_int($val), + self::PARAM_CHECK_OBJECT => \is_object($val), + self::PARAM_CHECK_CLASS => \is_object($val) && $item[4] !== null && ($val instanceof $item[4]), self::PARAM_CHECK_ARRAY_KEY => \is_int($val) || \is_string($val), self::PARAM_CHECK_ARRAY => \is_array($val), self::PARAM_CHECK_LIST => \is_array($val) && ($val === [] || array_is_list($val)), @@ -1993,6 +2002,7 @@ private static function executeSimpleScopePlan(array $plan, array $vars): ?Error continue; } + $registry = self::$registry ??= new TypeValidatorRegistry(); $err = $registry->validate($val, $item[2], '', $item[3]); if ($err !== null) { $formattedErr = ErrorFactory::createError($effectiveFunc . '(): Argument $' . $paramName . $err->getMessage()); @@ -2015,7 +2025,7 @@ private static function executeSimpleScopePlan(array $plan, array $vars): ?Error * @param array $types * @param array $sensitiveParams * - * @return list + * @return list */ private static function compileSimpleScopePlanItems(array $types, array $sensitiveParams): array { @@ -2023,15 +2033,46 @@ private static function compileSimpleScopePlanItems(array $types, array $sensiti foreach ($types as $paramName => $typeNode) { $isSensitive = $sensitiveParams[$paramName] ?? false; $checkKind = self::PARAM_CHECK_FALLBACK; + $extra = null; + $allowsNull = false; + $inner = $typeNode; - if ($typeNode instanceof IdentifierTypeNode) { - $checkKind = match (strtolower($typeNode->name)) { + while ($inner instanceof NullableTypeNode) { + $allowsNull = true; + $inner = $inner->type; + } + + if ($inner instanceof UnionTypeNode) { + $nonNullTypes = []; + foreach ($inner->types as $member) { + if (self::isNullTypeNode($member)) { + $allowsNull = true; + } elseif ($member instanceof NullableTypeNode) { + $allowsNull = true; + $nonNullTypes[] = $member->type; + } else { + $nonNullTypes[] = $member; + } + } + + if ($allowsNull && \count($nonNullTypes) === 1) { + $inner = $nonNullTypes[0]; + while ($inner instanceof NullableTypeNode) { + $inner = $inner->type; + } + } + } + + if ($inner instanceof IdentifierTypeNode) { + $name = $inner->name; + $checkKind = match (strtolower($name)) { 'int', 'integer' => self::PARAM_CHECK_INT, 'string' => self::PARAM_CHECK_STRING, 'positive-int' => self::PARAM_CHECK_POSITIVE_INT, 'non-empty-string' => self::PARAM_CHECK_NON_EMPTY_STRING, 'bool', 'boolean' => self::PARAM_CHECK_BOOL, 'float', 'double' => self::PARAM_CHECK_FLOAT, + 'object' => self::PARAM_CHECK_OBJECT, 'array-key' => self::PARAM_CHECK_ARRAY_KEY, 'array' => self::PARAM_CHECK_ARRAY, 'list' => self::PARAM_CHECK_LIST, @@ -2046,9 +2087,20 @@ private static function compileSimpleScopePlanItems(array $types, array $sensiti 'scalar' => self::PARAM_CHECK_SCALAR, default => self::PARAM_CHECK_FALLBACK, }; + + if ($checkKind === self::PARAM_CHECK_NULL || $checkKind === self::PARAM_CHECK_MIXED) { + $allowsNull = true; + } elseif ( + $checkKind === self::PARAM_CHECK_FALLBACK + && ! SpecialTypeResolver::isBuiltInTypeKeyword($name) + && ClassNameValidator::isValid($name) + ) { + $checkKind = self::PARAM_CHECK_CLASS; + $extra = $name; + } } - $items[] = [$paramName, $checkKind, $typeNode, $isSensitive]; + $items[] = [$paramName, $checkKind, $typeNode, $isSensitive, $extra, $allowsNull]; } return $items; diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index d34bca03..5cbc2cf6 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -970,6 +970,10 @@ private static function validateCallbackArguments( continue; } + if (IgnoreManager::isCallerIgnored()) { + break; + } + $handled = ViolationCollector::handle($err, 'callback', null); if ($handled instanceof ErrorMessage) { throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); @@ -1042,6 +1046,10 @@ private static function validateCallbackByRefMutations( continue; } + if (IgnoreManager::isCallerIgnored()) { + break; + } + $handled = ViolationCollector::handle($err, 'callback', null); if ($handled instanceof ErrorMessage) { throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); diff --git a/tests/Feature/ViolationConfigModeTest.php b/tests/Feature/ViolationConfigModeTest.php new file mode 100644 index 00000000..e39be23c --- /dev/null +++ b/tests/Feature/ViolationConfigModeTest.php @@ -0,0 +1,45 @@ + 'throw']); + $throwKey = CacheManager::getCacheKey($file); + + Config::set(['on_violation' => 'report']); + $reportKey = CacheManager::getCacheKey($file); + + Config::set(['on_violation' => 'warn']); + $warnKey = CacheManager::getCacheKey($file); + + expect($throwKey)->not->toBe($reportKey); + expect($reportKey)->toBe($warnKey); +}); + +it('reflects TYPEPHP_ON_VIOLATION env override in cache key and shares key with config mode', function () { + $file = __FILE__; + + Config::set(['on_violation' => 'report']); + $configReportKey = CacheManager::getCacheKey($file); + + Config::set(['on_violation' => 'throw']); + $throwKey = CacheManager::getCacheKey($file); + + $_ENV['TYPEPHP_ON_VIOLATION'] = 'report'; + CacheManager::reset(); + + try { + $envReportKey = CacheManager::getCacheKey($file); + } finally { + unset($_ENV['TYPEPHP_ON_VIOLATION']); + CacheManager::reset(); + } + + expect($envReportKey)->not->toBe($throwKey); + expect($envReportKey)->toBe($configReportKey); +}); diff --git a/tests/Internal/Docblock/DocblockNormalizerTest.php b/tests/Internal/Docblock/DocblockNormalizerTest.php index 5fb48371..b19e1b72 100644 --- a/tests/Internal/Docblock/DocblockNormalizerTest.php +++ b/tests/Internal/Docblock/DocblockNormalizerTest.php @@ -2,8 +2,12 @@ declare(strict_types=1); +use PhpParser\Node\Scalar\LNumber; +use TypePHP\Internal\Ast\TypeDeducer; +use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; +use TypePHP\Internal\RuntimeTypeChecker; describe('DocblockNormalizer', function () { test('returns docblock string unchanged when no special keywords or curly braces are present', function () { @@ -611,4 +615,101 @@ expect(DocblockNormalizer::normalize($doc))->toBe($expected); }); }); + + describe('Bare Type String Normalization (Without @ Tags)', function () { + test('normalizes bare custom class shapes into intersection shapes', function () { + expect(DocblockNormalizer::normalize('stdClass{id: int, name: string}')) + ->toBe('(stdClass&object{id: int, name: string})') + ; + + expect(DocblockNormalizer::normalize('list')) + ->toBe('list<(stdClass&object{id: positive-int, author: (User&object{name: string})})>') + ; + }); + + test('normalizes bare class constant keys in array shapes', function () { + expect(DocblockNormalizer::normalize('array{self::KEY_ID: int, Config::OPTIONAL?: bool}')) + ->toBe('array{"self::KEY_ID": int, "Config::OPTIONAL"?: bool}') + ; + }); + + test('normalizes bare unparenthesized nested and curried callables', function () { + expect(DocblockNormalizer::normalize('callable(int): callable(string): bool')) + ->toBe('callable(int): (callable(string): bool)') + ; + + expect(DocblockNormalizer::normalize('callable(int): callable(string): callable(float): int')) + ->toBe('callable(int): (callable(string): (callable(float): int))') + ; + }); + + test('normalizes bare callables with omitted return types', function () { + expect(DocblockNormalizer::normalize('callable(int $x)')) + ->toBe('callable(int $x): mixed') + ; + + expect(DocblockNormalizer::normalize('Closure()')) + ->toBe('Closure(): mixed') + ; + }); + + test('normalizes bare static Closure syntax', function () { + expect(DocblockNormalizer::normalize('(static Closure)(int): int')) + ->toBe('static-closure(int): int') + ; + + expect(DocblockNormalizer::normalize('static Closure(int): int')) + ->toBe('static-closure(int): int') + ; + }); + + test('normalizes bare unqualified int-mask-of wildcards', function () { + expect(DocblockNormalizer::normalize('int-mask-of')) + ->toBe('int-mask-of<"E_*">') + ; + }); + + test('normalizes bare variadic tuple spread syntax', function () { + expect(DocblockNormalizer::normalize('array{string, int, ...float[]}')) + ->toBe('array{string, int, ...}') + ; + + expect(DocblockNormalizer::normalize('array{string, ...list}')) + ->toBe('array{string, ...}') + ; + }); + + test('leaves plain bare types and tagless prose docblocks unchanged', function () { + expect(DocblockNormalizer::normalize('array')) + ->toBe('array') + ; + + $proseDoc = '/** Builds a Foo{bar} or callable(int) helper. */'; + expect(DocblockNormalizer::normalize($proseDoc)) + ->toBe($proseDoc) + ; + }); + + test('reproduces runtime failures on bare type strings in RuntimeTypeChecker and TypeDeducer', function () { + $badObj = (object) ['id' => -5]; + $shapeErr = RuntimeTypeChecker::checkVariable($badObj, 'stdClass{id: positive-int}', 'data', __FILE__); + expect($shapeErr)->toBeInstanceOf(ErrorMessage::class); + + $maskErr = RuntimeTypeChecker::checkConstant('TEST_MASK', 1 << 25, 'int-mask-of'); + expect($maskErr)->toBeInstanceOf(ErrorMessage::class); + + $curried = RuntimeTypeChecker::checkVariable( + static fn (int $a): Closure => static fn (string $b): string => 'not-a-bool', + 'callable(int): callable(string): bool', + 'fn', + __FILE__ + ); + expect($curried)->toBeInstanceOf(Closure::class); + $inner = $curried(1); + expect(fn () => $inner('hello'))->toThrow(TypeError::class); + + expect(TypeDeducer::deduceDimType('array{string, ...float[]}', new LNumber(3))) + ->toBe('float'); + }); + }); }); diff --git a/tests/Internal/Io/CacheManagerTest.php b/tests/Internal/Io/CacheManagerTest.php index 7f5d905d..d8c6582c 100644 --- a/tests/Internal/Io/CacheManagerTest.php +++ b/tests/Internal/Io/CacheManagerTest.php @@ -65,7 +65,17 @@ Config::set(['respect_ignore_tags' => true, 'on_violation' => 'throw']); $key = CacheManager::getCacheKey($file); - Config::set(['on_violation' => 'report', 'report_file' => '/tmp/report.json']); + Config::set(['report_file' => '/tmp/report.json', 'redact_values' => true, 'fail_on_report' => true]); + expect(CacheManager::getCacheKey($file))->toBe($key); + + Config::set(['on_violation' => 'report']); + $reportKey = CacheManager::getCacheKey($file); + expect($reportKey)->not()->toBe($key); + + Config::set(['on_violation' => 'warn']); + expect(CacheManager::getCacheKey($file))->toBe($reportKey); + + Config::set(['on_violation' => 'throw']); expect(CacheManager::getCacheKey($file))->toBe($key); Config::set(['respect_ignore_tags' => false]); diff --git a/tests/Internal/Io/StreamWrapperTest.php b/tests/Internal/Io/StreamWrapperTest.php index a4e7d274..030fd501 100644 --- a/tests/Internal/Io/StreamWrapperTest.php +++ b/tests/Internal/Io/StreamWrapperTest.php @@ -653,4 +653,146 @@ public function second() expect($transformed)->toContain('class MultiAnonFactory'); }); }); + + describe('Write-Mode Cache Invalidation & $openedPath Resolution', function () { + test('invalidates statCache when overwriting an existing .php file via file_put_contents()', function () { + StreamWrapper::register(); + + $tempDir = sys_get_temp_dir() . '/typephp_write_stat_' . uniqid(); + mkdir($tempDir, 0777, true); + $tempFile = $tempDir . '/dynamic.php'; + + try { + $initial = 'url_stat($tempFile, 0); + expect($statBefore)->toBeArray() + ->and($statBefore['size'])->toBe(\strlen($initial)) + ; + + $updated = 'url_stat($tempFile, 0); + expect($statAfter)->toBeArray() + ->and($statAfter['size'])->toBe(\strlen($updated)) + ; + } finally { + @unlink($tempFile); + @rmdir($tempDir); + } + }); + + test('invalidates statCache after writing via an r+ handle even if stat occurred after fopen()', function () { + StreamWrapper::register(); + + $tempDir = sys_get_temp_dir() . '/typephp_rplus_stat_' . uniqid(); + mkdir($tempDir, 0777, true); + $tempFile = $tempDir . '/rplus.php'; + + try { + $initial = 'not()->toBeFalse(); + + expect(filesize($tempFile))->toBe(\strlen($initial)); + + $updated = 'toBe(\strlen($updated)); + } finally { + @unlink($tempFile); + @rmdir($tempDir); + } + }); + + test('invalidates staticNegativeStatCache when creating a previously missing file under a vendor path', function () { + StreamWrapper::register(); + + $tempDir = sys_get_temp_dir() . '/typephp_vendor_neg_' . uniqid(); + $vendorPkgDir = $tempDir . '/vendor/acme/pkg'; + mkdir($vendorPkgDir, 0777, true); + $generatedFile = $vendorPkgDir . '/Generated.php'; + + try { + $wrapper = new StreamWrapper(); + expect($wrapper->url_stat($generatedFile, 0))->toBeFalse(); + + file_put_contents($generatedFile, 'url_stat($generatedFile, 0))->toBeArray(); + } finally { + @unlink($generatedFile); + @rmdir($vendorPkgDir); + @rmdir($tempDir . '/vendor/acme'); + @rmdir($tempDir . '/vendor'); + @rmdir($tempDir); + } + }); + + test('populates $openedPath and resolves files on include_path for STREAM_USE_PATH opens and includes', function () { + StreamWrapper::register(); + + $tempDir = sys_get_temp_dir() . '/typephp_incpath_' . uniqid(); + mkdir($tempDir, 0777, true); + $realDir = realpath($tempDir) ?: $tempDir; + $fileName = 'IncludePathFixture_' . uniqid() . '.php'; + $fullPath = $realDir . DIRECTORY_SEPARATOR . $fileName; + + file_put_contents($fullPath, "stream_open($fileName, 'r', STREAM_USE_PATH, $openedPath); + $wrapper->stream_close(); + + expect($opened)->toBeTrue() + ->and($openedPath)->not()->toBeNull() + ->and(str_replace('\\', '/', (string) realpath((string) $openedPath))) + ->toBe(str_replace('\\', '/', (string) realpath($fullPath))) + ; + + $canonicalDir = str_replace('\\', '/', $realDir); + Config::set([ + 'include' => [$canonicalDir . '/**'], + 'exclude' => ['vendor/**'], + ]); + + $openedIncludePath = null; + $included = $wrapper->stream_open( + $fileName, + 'r', + StreamWrapper::STREAM_OPEN_FOR_INCLUDE | STREAM_USE_PATH, + $openedIncludePath + ); + $content = $included ? $wrapper->stream_read(5000) : ''; + $wrapper->stream_close(); + + expect($included)->toBeTrue() + ->and($openedIncludePath)->not()->toBeNull() + ->and(str_replace('\\', '/', (string) realpath((string) $openedIncludePath))) + ->toBe(str_replace('\\', '/', (string) realpath($fullPath))) + ->and($content)->toContain('RuntimeTypeChecker::setupScope') + ; + } finally { + set_include_path($originalIncludePath); + @unlink($fullPath); + @rmdir($tempDir); + } + }); + }); }); diff --git a/tests/Internal/RuntimeTypeCheckerSimplePlanTest.php b/tests/Internal/RuntimeTypeCheckerSimplePlanTest.php new file mode 100644 index 00000000..401ccc45 --- /dev/null +++ b/tests/Internal/RuntimeTypeCheckerSimplePlanTest.php @@ -0,0 +1,111 @@ + new DateTimeImmutable(), + 'meta' => null, + 'anyObj' => new stdClass(), + 'limit' => 10, + 'tag' => null, + ]; + + expect(RuntimeTypeChecker::setupScope($fn, $validVars, $target))->toBeNull(); + + $ref = new ReflectionClass(RuntimeTypeChecker::class); + $plans = $ref->getProperty('simpleScopePlanCache')->getValue(); + expect($plans)->toHaveKey($fn); + + $itemsByName = []; + foreach ($plans[$fn]['items'] as $item) { + $itemsByName[$item[0]] = $item; + } + + $opClass = $ref->getConstant('PARAM_CHECK_CLASS'); + $opObject = $ref->getConstant('PARAM_CHECK_OBJECT'); + $opPositiveInt = $ref->getConstant('PARAM_CHECK_POSITIVE_INT'); + $opString = $ref->getConstant('PARAM_CHECK_STRING'); + + expect($itemsByName['date'][1])->toBe($opClass) + ->and($itemsByName['date'][4])->toBe(DateTimeInterface::class) + ->and($itemsByName['date'][5])->toBeFalse() + ->and($itemsByName['meta'][1])->toBe($opClass) + ->and($itemsByName['meta'][4])->toBe(stdClass::class) + ->and($itemsByName['meta'][5])->toBeTrue() + ->and($itemsByName['anyObj'][1])->toBe($opObject) + ->and($itemsByName['anyObj'][5])->toBeFalse() + ->and($itemsByName['limit'][1])->toBe($opPositiveInt) + ->and($itemsByName['limit'][5])->toBeTrue() + ->and($itemsByName['tag'][1])->toBe($opString) + ->and($itemsByName['tag'][5])->toBeTrue() + ; + + expect(RuntimeTypeChecker::setupScope($fn, [ + 'date' => new DateTime(), + 'meta' => new stdClass(), + 'anyObj' => new DateTimeImmutable(), + 'limit' => null, + 'tag' => 'ok', + ], $target))->toBeNull(); + + $badDate = RuntimeTypeChecker::setupScope($fn, [...$validVars, 'date' => new stdClass()], $target); + expect($badDate)->toBeInstanceOf(ErrorMessage::class) + ->and($badDate->getMessage())->toContain('DateTimeInterface') + ; + + $nullDate = RuntimeTypeChecker::setupScope($fn, [...$validVars, 'date' => null], $target); + expect($nullDate)->toBeInstanceOf(ErrorMessage::class) + ->and($nullDate->getMessage())->toContain('DateTimeInterface') + ; + + $badMeta = RuntimeTypeChecker::setupScope($fn, [...$validVars, 'meta' => new DateTimeImmutable()], $target); + expect($badMeta)->toBeInstanceOf(ErrorMessage::class) + ->and($badMeta->getMessage())->toContain('stdClass') + ; + + $badObj = RuntimeTypeChecker::setupScope($fn, [...$validVars, 'anyObj' => 'not-an-object'], $target); + expect($badObj)->toBeInstanceOf(ErrorMessage::class) + ->and($badObj->getMessage())->toContain('object') + ; + + $badLimit = RuntimeTypeChecker::setupScope($fn, [...$validVars, 'limit' => 0], $target); + expect($badLimit)->toBeInstanceOf(ErrorMessage::class) + ->and($badLimit->getMessage())->toContain('positive-int') + ; + }); +}); diff --git a/tests/Internal/Wrapper/CallableWrapperVariadicIgnoreTest.php b/tests/Internal/Wrapper/CallableWrapperVariadicIgnoreTest.php new file mode 100644 index 00000000..08202d78 --- /dev/null +++ b/tests/Internal/Wrapper/CallableWrapperVariadicIgnoreTest.php @@ -0,0 +1,138 @@ +parse(new TokenIterator($lexer->tokenize($signature))); + }; + + $caller = new class () { + /** + * @typephp-ignore + */ + public function invokeIgnoredVariadic(Closure $cb, mixed ...$args): void + { + $cb(...$args); + } + + public function invokeEnforcedVariadic(Closure $cb, mixed ...$args): void + { + $cb(...$args); + } + + /** + * @typephp-ignore + */ + public function invokeIgnoredVariadicByRef(Closure $cb, mixed &$a, mixed &$b): void + { + $cb($a, $b); + } + + public function invokeEnforcedVariadicByRef(Closure $cb, mixed &$a, mixed &$b): void + { + $cb($a, $b); + } + }; + + test('suppresses variadic callback argument violations when caller has @typephp-ignore', function () use ($parseCallableNode, $caller) { + $typeNode = $parseCallableNode('callable(positive-int ...$nums): void'); + $received = []; + + $wrapped = CallableWrapper::wrapTypeNode( + $typeNode, + static function (mixed ...$nums) use (&$received): void { + $received = $nums; + }, + 'VariadicCallback', + new TypeValidatorRegistry() + ); + + expect($wrapped)->toBeInstanceOf(Closure::class); + + $caller->invokeIgnoredVariadic($wrapped, 1, -5, 3); + expect($received)->toBe([1, -5, 3]); + + expect(fn () => $caller->invokeEnforcedVariadic($wrapped, 1, -5, 3)) + ->toThrow(TypePHPTypeError::class, 'positive-int') + ; + }); + + test('suppresses variadic by-reference callback mutation violations when caller has @typephp-ignore', function () use ($parseCallableNode, $caller) { + $typeNode = $parseCallableNode('callable(positive-int &...$nums): void'); + + $wrapped = CallableWrapper::wrapTypeNode( + $typeNode, + static function (mixed &...$nums): void { + $nums[1] = -99; + }, + 'VariadicRefCallback', + new TypeValidatorRegistry() + ); + + expect($wrapped)->toBeInstanceOf(Closure::class); + + $a = 10; + $b = 20; + $caller->invokeIgnoredVariadicByRef($wrapped, $a, $b); + expect($b)->toBe(-99); + + $c = 10; + $d = 20; + expect(fn () => $caller->invokeEnforcedVariadicByRef($wrapped, $c, $d)) + ->toThrow(TypePHPTypeError::class, 'positive-int') + ; + }); + + test('enforces variadic callback violations for ignored callers when respect_ignore_tags is disabled', function () use ($parseCallableNode, $caller) { + Config::set(['respect_ignore_tags' => false]); + + $argNode = $parseCallableNode('callable(positive-int ...$nums): void'); + $wrappedArg = CallableWrapper::wrapTypeNode( + $argNode, + static function (mixed ...$nums): void { + }, + 'VariadicCallback', + new TypeValidatorRegistry() + ); + + expect(fn () => $caller->invokeIgnoredVariadic($wrappedArg, 1, -5)) + ->toThrow(TypePHPTypeError::class, 'positive-int') + ; + + $refNode = $parseCallableNode('callable(positive-int &...$nums): void'); + $wrappedRef = CallableWrapper::wrapTypeNode( + $refNode, + static function (mixed &...$nums): void { + $nums[1] = -99; + }, + 'VariadicRefCallback', + new TypeValidatorRegistry() + ); + + $a = 10; + $b = 20; + expect(fn () => $caller->invokeIgnoredVariadicByRef($wrappedRef, $a, $b)) + ->toThrow(TypePHPTypeError::class, 'positive-int') + ; + }); +}); diff --git a/tests/TypeChecking/Generics/InlineVarUnboundFallbackTest.php b/tests/TypeChecking/Generics/InlineVarUnboundFallbackTest.php new file mode 100644 index 00000000..a586181a --- /dev/null +++ b/tests/TypeChecking/Generics/InlineVarUnboundFallbackTest.php @@ -0,0 +1,165 @@ + + */ +final class NoctudStaticFactoryMapFixture implements ReproMapInterface +{ + /** @use ReproMapLogic */ + use ReproMapLogic; + + public function __construct() + { + $this->store = ReproHashStore::fromAssoc([]); + } + + /** + * @template NK of string|int|bool|float|object + * @template NV + * + * @param iterable|Closure(): iterable $data + * + * @return ReproMapInterface + */ + public static function of(iterable|Closure $data = []): ReproMapInterface + { + /** @var NoctudStaticFactoryMapFixture $map */ + $map = new self(); + + if ($data instanceof Closure) { + $reflector = new ReflectionClass(ReproHashStore::class); + $map->store = $reflector->newLazyProxy( + fn (ReproHashStore $object): ReproHashStore => $object::fromAssoc($data()) + ); + } elseif ($data instanceof ReproHashStore) { + $map->store = clone $data; + } else { + $map->store = ReproHashStore::fromAssoc($data); + } + + return $map; + } + + /** + * Mirrors Noctud MapLogic::takeFirst(0) returning newMapOf([]). + * + * @return ReproMapInterface + */ + public function takeFirst(int $n = 1): ReproMapInterface + { + if ($n <= 0) { + return self::of([]); + } + + return self::of(clone $this->store); + } + + /** + * Mirrors Noctud MapLogic::sortedByKey() cloning $this->store and returning newMapOf($store). + * + * @return ReproMapInterface + */ + public function sortedByKey(): ReproMapInterface + { + $store = clone $this->store; + + return self::of($store); + } + + /** + * @return ReproKeyValueStore + */ + public function getStore(): ReproKeyValueStore + { + return $this->store; + } +} + +/** + * Mirrors Noctud's ImmutableLazyHashMapTest::mapOf(). + * + * @template K of string|int|bool|float|object + * @template V + * + * @param iterable|Closure(): iterable $data + * + * @return ReproMapInterface + */ +function reproNoctudLazyStaticMapOf(iterable|Closure $data): ReproMapInterface +{ + if (! \is_callable($data)) { + return NoctudStaticFactoryMapFixture::of(fn () => $data); + } + + return NoctudStaticFactoryMapFixture::of($data); +} + +/** + * Negative control: explicitly wide union bound (NOT an unbound template) must still fail invariant return. + * + * @return ReproMapInterface + */ +function reproReturnExplicitlyWideMapAsNarrow(): ReproMapInterface +{ + /** @var NoctudStaticFactoryMapFixture $wide */ + $wide = new NoctudStaticFactoryMapFixture(); + + return $wide; +} + +describe('Noctud Static Factory Inline @var Unbound Template Fallback', function () { + test('lazy mapOf() via static::of() refines both map and lazy store without initializing proxy', function () { + $map = reproNoctudLazyStaticMapOf(['a' => 1, 'b' => 2]); + \assert($map instanceof NoctudStaticFactoryMapFixture); + + $storeRef = new ReflectionClass(ReproHashStore::class); + + expect($storeRef->isUninitializedLazyObject($map->getStore()))->toBeTrue() + ->and(TypePHP::getGenericTypes($map))->toBe(['K' => 'string', 'V' => 'int']) + ->and(TypePHP::getGenericTypes($map->getStore()))->toBe(['K' => 'string', 'V' => 'int']) + ; + + expect(iterator_to_array($map->keys))->toBe(['a', 'b']); + + $sorted = $map->sortedByKey(); + expect(iterator_to_array($sorted->keys))->toBe(['a', 'b']); + }); + + test('takeFirst(0) returning empty static::of([]) specializes to caller map types', function () { + $map = NoctudStaticFactoryMapFixture::of(['a' => 1, 'b' => 2]); + \assert($map instanceof NoctudStaticFactoryMapFixture); + + $empty = $map->takeFirst(0); + + expect(TypePHP::getGenericTypes($empty))->toBe(['K' => 'string', 'V' => 'int']); + }); + + test('inline @var narrowing on empty static::of([]) succeeds', function () { + /** @var ReproMapInterface $map */ + $map = NoctudStaticFactoryMapFixture::of([]); + + expect(TypePHP::getGenericTypes($map))->toBe(['K' => 'string', 'V' => 'string']); + }); + + test('keeps strict invariance for explicitly typed wide union bounds', function () { + expect(fn () => reproReturnExplicitlyWideMapAsNarrow()) + ->toThrow(TypePHPTypeError::class, 'expects ReproMapInterface') + ; + }); +}); diff --git a/tests/TypeChecking/Generics/InterfaceGenericVarianceTest.php b/tests/TypeChecking/Generics/InterfaceGenericVarianceTest.php new file mode 100644 index 00000000..aca60c76 --- /dev/null +++ b/tests/TypeChecking/Generics/InterfaceGenericVarianceTest.php @@ -0,0 +1,420 @@ + + */ +abstract class VarianceBaseRepository implements VarianceRepositoryInterface +{ + /** + * @var array + */ + protected array $items = []; + + public function save(mixed $item): void + { + $this->items[] = $item; + } +} + +/** + * @extends VarianceBaseRepository + */ +class VarianceUserRepository extends VarianceBaseRepository +{ +} + +/** + * @extends VarianceBaseRepository + */ +class VarianceAdminRepository extends VarianceBaseRepository +{ +} + +/** + * @extends VarianceBaseRepository + */ +class VarianceEntityRepository extends VarianceBaseRepository +{ +} + +/** + * @template TModel of VarianceEntity + * + * @implements VarianceRepositoryInterface + */ +abstract class RenamedTemplateBaseRepository implements VarianceRepositoryInterface +{ + public function save(mixed $item): void + { + } +} + +/** + * @extends RenamedTemplateBaseRepository + */ +class RenamedTemplateUserRepository extends RenamedTemplateBaseRepository +{ +} + +/** + * @template T of VarianceEntity + */ +class VarianceUserService +{ + /** + * @param VarianceRepositoryInterface $repo + */ + public function __construct(private VarianceRepositoryInterface $repo) + { + } + + /** + * @return VarianceRepositoryInterface + */ + public function getRepo(): VarianceRepositoryInterface + { + return $this->repo; + } +} + +/** + * @template-covariant T of VarianceEntity + */ +class CovariantBox +{ + /** + * @param T $value + */ + public function __construct(private mixed $value) + { + } + + /** + * @return T + */ + public function get(): mixed + { + return $this->value; + } +} + +/** + * @template-contravariant T of VarianceEntity + */ +class ContravariantSink +{ + /** + * @param T $value + */ + public function consume(mixed $value): void + { + } +} + +/** + * @template T of VarianceEntity + */ +class InvariantBox +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } +} + +/** + * @param VarianceUserService $service + */ +function acceptAdminUserService(VarianceUserService $service): void +{ +} + +/** + * @return VarianceUserService + */ +function returnAdminUserService(VarianceUserRepository $repo): VarianceUserService +{ + return new VarianceUserService($repo); +} + +/** + * @param CovariantBox $box + */ +function acceptCovariantUserBox(CovariantBox $box): void +{ +} + +/** + * @param CovariantBox $box + */ +function acceptCovariantAdminBox(CovariantBox $box): void +{ +} + +/** + * @param ContravariantSink $sink + */ +function acceptContravariantAdminSink(ContravariantSink $sink): void +{ +} + +/** + * @param ContravariantSink $sink + */ +function acceptContravariantUserSink(ContravariantSink $sink): void +{ +} + +/** + * @param InvariantBox $box + */ +function acceptUseSiteCovariantUserBox(InvariantBox $box): void +{ +} + +/** + * @param InvariantBox $box + */ +function acceptUseSiteCovariantAdminBox(InvariantBox $box): void +{ +} + +/** + * @param InvariantBox $box + */ +function acceptUseSiteContravariantAdminBox(InvariantBox $box): void +{ +} + +/** + * @param InvariantBox $box + */ +function acceptUseSiteContravariantUserBox(InvariantBox $box): void +{ +} + +/** + * @param InvariantBox<*> $box + */ +function acceptUseSiteWildcardBox(InvariantBox $box): void +{ +} + +describe('Interface Generic Invariance (Test 5 Reproduction)', function () { + test('allows inherited concrete repository matching service template', function () { + $userRepo = new VarianceUserRepository(); + $userRepo->save(new VarianceUser('Alice')); + $userRepo->save(new VarianceAdmin('Bob')); + + /** @var VarianceUserService $service */ + $service = new VarianceUserService($userRepo); + + expect($service->getRepo())->toBe($userRepo); + }); + + test('rejects passing RepositoryInterface into UserService via unnamed @var', function () { + $userRepo = new VarianceUserRepository(); + $userRepo->save(new VarianceUser('Alice')); + + expect(function () use ($userRepo): void { + /** @var VarianceUserService */ + $badService = new VarianceUserService($userRepo); + })->toThrow(TypeError::class); + }); + + test('rejects passing RepositoryInterface into UserService via named @var', function () { + $userRepo = new VarianceUserRepository(); + + expect(function () use ($userRepo): void { + /** @var VarianceUserService $badService */ + $badService = new VarianceUserService($userRepo); + })->toThrow(TypeError::class); + }); + + test('rejects passing UserService into @param UserService', function () { + $userRepo = new VarianceUserRepository(); + + expect(function () use ($userRepo): void { + acceptAdminUserService(new VarianceUserService($userRepo)); + })->toThrow(TypeError::class); + }); + + test('rejects returning UserService from @return UserService', function () { + $userRepo = new VarianceUserRepository(); + + expect(function () use ($userRepo): void { + returnAdminUserService($userRepo); + })->toThrow(TypeError::class); + }); + + test('rejects supertype specialization RepositoryInterface into UserService under invariance', function () { + $userRepo = new VarianceUserRepository(); + + expect(function () use ($userRepo): void { + /** @var VarianceUserService $badService */ + $badService = new VarianceUserService($userRepo); + })->toThrow(TypeError::class); + }); + + test('rejects subtype specialization RepositoryInterface into UserService under invariance', function () { + $adminRepo = new VarianceAdminRepository(); + + expect(function () use ($adminRepo): void { + /** @var VarianceUserService $badService */ + $badService = new VarianceUserService($adminRepo); + })->toThrow(TypeError::class); + }); + + test('rejects specialization equal to upper bound RepositoryInterface into UserService', function () { + $entityRepo = new VarianceEntityRepository(); + + expect(function () use ($entityRepo): void { + /** @var VarianceUserService $badService */ + $badService = new VarianceUserService($entityRepo); + })->toThrow(TypeError::class); + }); + + test('rejects RepositoryInterface into UserService even when intermediate class renames template parameter', function () { + $userRepo = new RenamedTemplateUserRepository(); + + expect(function () use ($userRepo): void { + /** @var VarianceUserService $badService */ + $badService = new VarianceUserService($userRepo); + })->toThrow(TypeError::class); + }); +}); + +describe('Declaration-Site Covariance (@template-covariant)', function () { + test('allows subtype CovariantBox where CovariantBox is expected', function () { + /** @var CovariantBox $adminBox */ + $adminBox = new CovariantBox(new VarianceAdmin('Bob')); + + acceptCovariantUserBox($adminBox); + + expect($adminBox->get())->toBeInstanceOf(VarianceAdmin::class); + }); + + test('rejects supertype CovariantBox where CovariantBox is expected', function () { + /** @var CovariantBox $userBox */ + $userBox = new CovariantBox(new VarianceUser('Alice')); + + expect(function () use ($userBox): void { + acceptCovariantAdminBox($userBox); + })->toThrow(TypeError::class); + }); + + test('rejects upper-bound supertype CovariantBox where CovariantBox is expected', function () { + /** @var CovariantBox $entityBox */ + $entityBox = new CovariantBox(new VarianceEntity()); + + expect(function () use ($entityBox): void { + acceptCovariantAdminBox($entityBox); + })->toThrow(TypeError::class); + }); +}); + +describe('Declaration-Site Contravariance (@template-contravariant)', function () { + test('allows supertype ContravariantSink where ContravariantSink is expected', function () { + /** @var ContravariantSink $userSink */ + $userSink = new ContravariantSink(); + + acceptContravariantAdminSink($userSink); + + expect(true)->toBeTrue(); + }); + + test('rejects subtype ContravariantSink where ContravariantSink is expected', function () { + /** @var ContravariantSink $adminSink */ + $adminSink = new ContravariantSink(); + + expect(function () use ($adminSink): void { + acceptContravariantUserSink($adminSink); + })->toThrow(TypeError::class); + }); +}); + +describe('Use-Site Variance (covariant, contravariant, wildcard)', function () { + test('allows subtype InvariantBox into InvariantBox', function () { + /** @var InvariantBox $adminBox */ + $adminBox = new InvariantBox(new VarianceAdmin('Bob')); + + acceptUseSiteCovariantUserBox($adminBox); + + expect($adminBox->value)->toBeInstanceOf(VarianceAdmin::class); + }); + + test('rejects supertype InvariantBox into InvariantBox', function () { + /** @var InvariantBox $userBox */ + $userBox = new InvariantBox(new VarianceUser('Alice')); + + expect(function () use ($userBox): void { + acceptUseSiteCovariantAdminBox($userBox); + })->toThrow(TypeError::class); + }); + + test('allows supertype InvariantBox into InvariantBox', function () { + /** @var InvariantBox $userBox */ + $userBox = new InvariantBox(new VarianceUser('Alice')); + + acceptUseSiteContravariantAdminBox($userBox); + + expect($userBox->value)->toBeInstanceOf(VarianceUser::class); + }); + + test('rejects subtype InvariantBox into InvariantBox', function () { + /** @var InvariantBox $adminBox */ + $adminBox = new InvariantBox(new VarianceAdmin('Bob')); + + expect(function () use ($adminBox): void { + acceptUseSiteContravariantUserBox($adminBox); + })->toThrow(TypeError::class); + }); + + test('allows any specialization into InvariantBox<*>', function () { + /** @var InvariantBox $userBox */ + $userBox = new InvariantBox(new VarianceUser('Alice')); + /** @var InvariantBox $adminBox */ + $adminBox = new InvariantBox(new VarianceAdmin('Bob')); + + acceptUseSiteWildcardBox($userBox); + acceptUseSiteWildcardBox($adminBox); + + expect(true)->toBeTrue(); + }); +}); From 8bdc4191e1a0b9ad4c8d71707d8dbffca22fef65 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 11:28:31 +0800 Subject: [PATCH 02/15] Refactor template binding retrieval to use getConcreteInstanceBindings method across InlineChecker, ParamChecker, and ReturnChecker; add InheritedTemplateBoundFallbackTest for enhanced type checking --- src/Internal/Checker/InlineChecker.php | 4 +- src/Internal/Checker/ParamChecker.php | 2 +- src/Internal/Checker/ReturnChecker.php | 2 +- src/Internal/Generics/TemplateManager.php | 116 +++++++++- .../InheritedTemplateBoundFallbackTest.php | 205 ++++++++++++++++++ 5 files changed, 314 insertions(+), 15 deletions(-) create mode 100644 tests/TypeChecking/Generics/InheritedTemplateBoundFallbackTest.php diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index c618759b..f34299f9 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -220,7 +220,7 @@ public static function checkVariable( $preExistingBindings = null; if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $typeNode instanceof GenericTypeNode) { - $preExistingBindings = TemplateManager::$instanceTemplateBindings[$value] ?? []; + $preExistingBindings = TemplateManager::getConcreteInstanceBindings($value); } if ($typeNode instanceof GenericTypeNode && Config::isInlineGenericsEnabled() && \is_object($value)) { @@ -535,7 +535,7 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string $preExistingBindings = null; if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $typeNode instanceof GenericTypeNode) { - $preExistingBindings = TemplateManager::$instanceTemplateBindings[$value] ?? []; + $preExistingBindings = TemplateManager::getConcreteInstanceBindings($value); } try { diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 3742dc08..800ffb2d 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -2540,7 +2540,7 @@ private static function validateSingleParam( $preExistingBindings = null; if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($val) && $typeNode instanceof GenericTypeNode) { - $preExistingBindings = TemplateManager::$instanceTemplateBindings[$val] ?? []; + $preExistingBindings = TemplateManager::getConcreteInstanceBindings($val); } $err = $registry->validate($val, $typeNode, $effectiveFunction . '(): Argument $' . $paramName, $isSensitive); diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index 207a5207..9ffd9eb3 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -541,7 +541,7 @@ private static function evaluateReturn( $preExistingBindings = null; if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $resolvedType instanceof GenericTypeNode) { - $preExistingBindings = TemplateManager::$instanceTemplateBindings[$value] ?? []; + $preExistingBindings = TemplateManager::getConcreteInstanceBindings($value); } $err = $registry->validate($value, $resolvedType, 'Return value'); diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index e29343fd..5bf55152 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -101,6 +101,14 @@ final class TemplateManager */ private static array $classInheritedBindingsCache = []; + /** + * Cache for inherited template names whose class-level binding came from a template bound/default fallback: + * [$className][$templateName] => true. + * + * @var array> + */ + private static array $classInheritedFallbackKeysCache = []; + /** * In-memory 2D cache for subclass hierarchy (is_a) lookups: [$sub][$super] => bool. * @@ -655,6 +663,7 @@ public static function reset(): void self::$classTemplateDefaultsCache = []; self::$templateVariancesCache = []; self::$classInheritedBindingsCache = []; + self::$classInheritedFallbackKeysCache = []; self::$classInheritedRawMappingsCache = []; self::$subclassCache = []; self::$realTypeSymbolCache = []; @@ -736,6 +745,23 @@ public static function getFallbackBoundTemplates(object $instance): array : []; } + /** + * Returns only concretely bound (non-fallback) template bindings currently attached to an instance. + * + * @return array + */ + public static function getConcreteInstanceBindings(object $instance): array + { + if (self::$instanceTemplateBindings === null || ! isset(self::$instanceTemplateBindings[$instance])) { + return []; + } + + $bindings = self::$instanceTemplateBindings[$instance]; + $fallbacks = self::$fallbackBoundTemplates[$instance] ?? []; + + return $fallbacks !== [] ? array_diff_key($bindings, $fallbacks) : $bindings; + } + /** * Marks newly bound template slots on an instance as fallback-derived when populated from * unbound template parameters in a return contract. @@ -996,8 +1022,10 @@ public static function getClassInheritedBindings(string $className): array } $rawBindings = []; - $resolved = self::computeClassInheritedBindings($className, $rawBindings); + $fallbackKeys = []; + $resolved = self::computeClassInheritedBindings($className, $rawBindings, $fallbackKeys); self::$classInheritedRawMappingsCache[$className] = $rawBindings; + self::$classInheritedFallbackKeysCache[$className] = $fallbackKeys; return self::$classInheritedBindingsCache[$className] = $resolved; } @@ -1579,6 +1607,7 @@ public static function bindInstanceFromNode( && $plan['allStaticValid'] && ! $forceBind && ! $refineOnly + && (self::$fallbackBoundTemplates === null || ! isset(self::$fallbackBoundTemplates[$instance])) ) { $allFastMatched = true; @@ -2401,7 +2430,15 @@ private static function bindSingleTemplateArgument( $existingTypeNode = $existingBindings[$templateName]; $valid = self::checkVariance($existingTypeNode, $expectedTypeNode, $variance); - if (! $valid) { + if ($valid) { + $isParamContext = str_contains($context, 'Argument '); + if (! $isWildcardOrMixed && ! $refineOnly && ! $isParamContext && self::isFallbackBound($instance, $templateName)) { + $bindings = self::$instanceTemplateBindings[$instance] ?? []; + $bindings[$templateName] = $expectedTypeNode; + self::$instanceTemplateBindings[$instance] = $bindings; + self::clearFallbackBound($instance, $templateName); + } + } else { if (($forceBind && ! $refineOnly) || ($isReturnContext && self::isGeneratorInferred($instance))) { $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; @@ -2410,9 +2447,13 @@ private static function bindSingleTemplateArgument( foreach ($rawMappings as $tName => $rawNode) { if (DocblockParser::typeReferencesTemplate($rawNode, [$templateName => true])) { $bindings[$tName] = TemplateSubstitutor::substitute($rawNode, $bindings); + if (! $isWildcardOrMixed && ! $refineOnly) { + self::clearFallbackBound($instance, $tName); + } } } + self::$instanceTemplateBindings ??= new WeakMap(); self::$instanceTemplateBindings[$instance] = $bindings; self::clearFallbackBound($instance, $templateName); @@ -2441,9 +2482,13 @@ private static function bindSingleTemplateArgument( foreach ($rawMappings as $tName => $rawNode) { if (DocblockParser::typeReferencesTemplate($rawNode, [$templateName => true])) { $bindings[$tName] = TemplateSubstitutor::substitute($rawNode, $bindings); + if (! $isWildcardOrMixed && ! $refineOnly) { + self::clearFallbackBound($instance, $tName); + } } } + self::$instanceTemplateBindings ??= new WeakMap(); self::$instanceTemplateBindings[$instance] = $bindings; self::clearFallbackBound($instance, $templateName); @@ -2511,6 +2556,9 @@ private static function bindSingleTemplateArgument( foreach ($rawMappings as $tName => $rawNode) { if (DocblockParser::typeReferencesTemplate($rawNode, [$templateName => true])) { $bindings[$tName] = TemplateSubstitutor::substitute($rawNode, $bindings); + if (! $isWildcardOrMixed && ! $refineOnly) { + self::clearFallbackBound($instance, $tName); + } } } @@ -2675,13 +2723,16 @@ public static function resolveInheritedTemplates(object $instance, string $targe if (! isset(self::$classInheritedBindingsCache[$actualClassName])) { $rawBindings = []; - $resolvedClassBindings = self::computeClassInheritedBindings($actualClassName, $rawBindings); + $fallbackKeys = []; + $resolvedClassBindings = self::computeClassInheritedBindings($actualClassName, $rawBindings, $fallbackKeys); self::$classInheritedBindingsCache[$actualClassName] = $resolvedClassBindings; self::$classInheritedRawMappingsCache[$actualClassName] = $rawBindings; + self::$classInheritedFallbackKeysCache[$actualClassName] = $fallbackKeys; } $cachedBindings = self::$classInheritedBindingsCache[$actualClassName]; $rawMappings = self::$classInheritedRawMappingsCache[$actualClassName] ?? []; + $inheritedFallbackKeys = self::$classInheritedFallbackKeysCache[$actualClassName] ?? []; $existing = self::$instanceTemplateBindings[$instance] ?? []; if ($cachedBindings === [] && $rawMappings === []) { @@ -2693,39 +2744,61 @@ public static function resolveInheritedTemplates(object $instance, string $targe if ($existing === []) { if ($cachedBindings !== []) { self::$instanceTemplateBindings[$instance] = $cachedBindings; + foreach ($inheritedFallbackKeys as $fbName => $_) { + self::markFallbackBound($instance, $fbName); + } } return; } $specializedBindings = []; + $newFallbackKeys = []; + $existingFallbacks = self::getFallbackBoundTemplates($instance); foreach ($cachedBindings as $tName => $fallbackTypeNode) { $rawNode = $rawMappings[$tName] ?? $fallbackTypeNode; if (DocblockParser::typeReferencesTemplate($rawNode, $existing)) { $specializedBindings[$tName] = TemplateSubstitutor::substitute($rawNode, $existing); + if ($existingFallbacks !== [] && DocblockParser::typeReferencesTemplate($rawNode, $existingFallbacks)) { + $newFallbackKeys[$tName] = true; + } } else { - $specializedBindings[$tName] = $existing[$tName] ?? $fallbackTypeNode; + if (isset($existing[$tName])) { + $specializedBindings[$tName] = $existing[$tName]; + } else { + $specializedBindings[$tName] = $fallbackTypeNode; + if (isset($inheritedFallbackKeys[$tName])) { + $newFallbackKeys[$tName] = true; + } + } } } foreach ($rawMappings as $tName => $rawNode) { if (! isset($specializedBindings[$tName]) && DocblockParser::typeReferencesTemplate($rawNode, $existing)) { $specializedBindings[$tName] = TemplateSubstitutor::substitute($rawNode, $existing); + if ($existingFallbacks !== [] && DocblockParser::typeReferencesTemplate($rawNode, $existingFallbacks)) { + $newFallbackKeys[$tName] = true; + } } } $merged = [...$existing, ...$specializedBindings]; if ($merged !== [] && $merged !== $existing) { self::$instanceTemplateBindings[$instance] = $merged; + foreach ($newFallbackKeys as $fbName => $_) { + self::markFallbackBound($instance, $fbName); + } } } /** * @param array $rawBindings + * @param array $fallbackKeys * * @return array */ - private static function computeClassInheritedBindings(string $actualClassName, array &$rawBindings = []): array + private static function computeClassInheritedBindings(string $actualClassName, array &$rawBindings = [], array &$fallbackKeys = []): array { /** @var array $bindings */ $bindings = []; @@ -2765,7 +2838,8 @@ private static function computeClassInheritedBindings(string $actualClassName, a $actualClassName, $bindings, $rawBindings, - $rootDeclaredTemplates + $rootDeclaredTemplates, + $fallbackKeys ); } } @@ -2783,6 +2857,7 @@ private static function computeClassInheritedBindings(string $actualClassName, a * @param array $bindings * @param array $rawBindings * @param array $rootDeclaredTemplates + * @param array $fallbackKeys * @param \ReflectionClass $hierClass */ private static function collectInheritedGenericTagBindings( @@ -2792,7 +2867,8 @@ private static function collectInheritedGenericTagBindings( string $actualClassName, array &$bindings, array &$rawBindings = [], - array $rootDeclaredTemplates = [] + array $rootDeclaredTemplates = [], + array &$fallbackKeys = [] ): void { $parentName = SpecialTypeResolver::resolveFqcn((string) $genericTypeNode->type, $hierClass); $isHierarchyMember = is_a($actualClassName, $parentName, true) || trait_exists($parentName); @@ -2841,14 +2917,23 @@ private static function collectInheritedGenericTagBindings( foreach ($parentTemplateNames as $idx => $templateName) { if (isset($normalizedGenericTypes[$idx])) { + $usedFallback = false; $typeArg = $normalizedGenericTypes[$idx]; if ($hierAliases !== []) { $typeArg = DocblockParser::substituteAliases($typeArg, $hierAliases); } if ($rawBindings !== []) { - $typeArg = TemplateSubstitutor::substitute($typeArg, $rawBindings); + $subArg = TemplateSubstitutor::substitute($typeArg, $rawBindings); + if ($subArg !== $typeArg && $fallbackKeys !== [] && DocblockParser::typeReferencesTemplate($typeArg, $fallbackKeys)) { + $usedFallback = true; + } + $typeArg = $subArg; } elseif ($bindings !== []) { - $typeArg = TemplateSubstitutor::substitute($typeArg, $bindings); + $subArg = TemplateSubstitutor::substitute($typeArg, $bindings); + if ($subArg !== $typeArg && $fallbackKeys !== [] && DocblockParser::typeReferencesTemplate($typeArg, $fallbackKeys)) { + $usedFallback = true; + } + $typeArg = $subArg; } $resolved = self::resolveTypeNodeAst($typeArg, $hierClass); @@ -2893,7 +2978,10 @@ private static function collectInheritedGenericTagBindings( } if (\count($boundOnlyFallbacks) === \count($rootDeclaredTemplates)) { - $bindings[$templateName] ??= TemplateSubstitutor::substitute($resolved, $boundOnlyFallbacks); + if (! isset($bindings[$templateName])) { + $bindings[$templateName] = TemplateSubstitutor::substitute($resolved, $boundOnlyFallbacks); + $fallbackKeys[$templateName] = true; + } } continue; @@ -2901,9 +2989,15 @@ private static function collectInheritedGenericTagBindings( if (DocblockParser::typeReferencesTemplate($resolved, $declaredTemplateNames) && $hierFallbackBindings !== []) { $resolved = TemplateSubstitutor::substitute($resolved, $hierFallbackBindings); + $usedFallback = true; } - $bindings[$templateName] ??= $resolved; + if (! isset($bindings[$templateName])) { + $bindings[$templateName] = $resolved; + if ($usedFallback) { + $fallbackKeys[$templateName] = true; + } + } } } } catch (\Throwable $e) { diff --git a/tests/TypeChecking/Generics/InheritedTemplateBoundFallbackTest.php b/tests/TypeChecking/Generics/InheritedTemplateBoundFallbackTest.php new file mode 100644 index 00000000..cd736283 --- /dev/null +++ b/tests/TypeChecking/Generics/InheritedTemplateBoundFallbackTest.php @@ -0,0 +1,205 @@ +). + * + * @template TKey of array-key + * @template TModel of EloquentModelFixture + * + * @extends BaseSupportCollectionFixture + */ +class VendorEloquentCollectionFixture extends BaseSupportCollectionFixture +{ + /** + * @typephp-ignore + */ + public static function rawFromVendor(): self + { + return new self(); + } +} + +/** + * Subclass without its own docblock, exercising intermediate hierarchy fallback ($hierFallbackBindings). + */ +class SubVendorEloquentCollectionFixture extends VendorEloquentCollectionFixture +{ + /** + * @typephp-ignore + */ + public static function rawSubFromVendor(): self + { + return new self(); + } +} + +/** + * Concrete non-generic subclass explicitly locking TModel to EloquentModelFixture. + * + * @extends BaseSupportCollectionFixture + */ +class ConcreteModelCollectionFixture extends BaseSupportCollectionFixture +{ +} + +final class EloquentCollectionConsumerFixture +{ + /** + * @return BaseSupportCollectionFixture + */ + public function queryCandidateTherapists(): BaseSupportCollectionFixture + { + return VendorEloquentCollectionFixture::rawFromVendor(); + } + + /** + * @return BaseSupportCollectionFixture + */ + public function querySubCandidateTherapists(): BaseSupportCollectionFixture + { + return SubVendorEloquentCollectionFixture::rawSubFromVendor(); + } + + /** + * @param BaseSupportCollectionFixture $therapists + */ + public function acceptTherapists(BaseSupportCollectionFixture $therapists): void + { + } + + /** + * @param BaseSupportCollectionFixture $rooms + */ + public function acceptRooms(BaseSupportCollectionFixture $rooms): void + { + } + + /** + * @param BaseSupportCollectionFixture $models + */ + public function acceptModels(BaseSupportCollectionFixture $models): void + { + } + + /** + * @return BaseSupportCollectionFixture + */ + public function invalidReturnAsStrings(): BaseSupportCollectionFixture + { + return VendorEloquentCollectionFixture::rawFromVendor(); + } + + /** + * Explicitly promises Collection (not specialized to Therapist). + * + * @return BaseSupportCollectionFixture + */ + public function returnExplicitlyWideModels(): BaseSupportCollectionFixture + { + return VendorEloquentCollectionFixture::rawFromVendor(); + } + + /** + * Concrete non-generic ModelCollection cannot satisfy Collection. + * + * @return BaseSupportCollectionFixture + */ + public function invalidReturnConcreteModelCollection(): BaseSupportCollectionFixture + { + return new ConcreteModelCollectionFixture(); + } +} + +describe('Inherited Bounded Template Fallback Specialization (Laravel Eloquent Collection Pattern)', function () { + test('specializes uninstrumented vendor EloquentCollection to @return Collection', function () { + $service = new EloquentCollectionConsumerFixture(); + + $therapists = $service->queryCandidateTherapists(); + $service->acceptTherapists($therapists); + + expect(TypePHP::getGenericType($therapists, 'TKey'))->toBe('int') + ->and(TypePHP::getGenericType($therapists, 'TValue'))->toBe(TherapistModelFixture::class) + ; + }); + + test('specializes subclass of vendor EloquentCollection via intermediate hierarchy fallback', function () { + $service = new EloquentCollectionConsumerFixture(); + + $therapists = $service->querySubCandidateTherapists(); + $service->acceptTherapists($therapists); + + expect(TypePHP::getGenericType($therapists, 'TKey'))->toBe('int') + ->and(TypePHP::getGenericType($therapists, 'TValue'))->toBe(TherapistModelFixture::class) + ; + }); + + test('specializes uninstrumented vendor EloquentCollection via @param and inline @var', function () { + $service = new EloquentCollectionConsumerFixture(); + + $directParamCol = VendorEloquentCollectionFixture::rawFromVendor(); + $service->acceptTherapists($directParamCol); + expect(TypePHP::getGenericType($directParamCol, 'TKey'))->toBe('int') + ->and(TypePHP::getGenericType($directParamCol, 'TValue'))->toBe(TherapistModelFixture::class) + ; + + /** @var BaseSupportCollectionFixture $inlineTherapists */ + $inlineTherapists = VendorEloquentCollectionFixture::rawFromVendor(); + $service->acceptTherapists($inlineTherapists); + expect(TypePHP::getGenericType($inlineTherapists, 'TKey'))->toBe('int') + ->and(TypePHP::getGenericType($inlineTherapists, 'TValue'))->toBe(TherapistModelFixture::class) + ; + }); + + test('retains strict covariance and invariance after specialization and rejects invalid subtypes', function () { + $service = new EloquentCollectionConsumerFixture(); + + $therapists = $service->queryCandidateTherapists(); + $service->acceptModels($therapists); + + expect(fn () => $service->acceptRooms($therapists)) + ->toThrow(TypePHPTypeError::class, 'covariant ' . RoomModelFixture::class) + ; + + expect(fn () => $service->invalidReturnAsStrings()) + ->toThrow(TypePHPTypeError::class, 'covariant string') + ; + + $models = $service->returnExplicitlyWideModels(); + expect(fn () => $service->acceptTherapists($models)) + ->toThrow(TypePHPTypeError::class, 'covariant ' . TherapistModelFixture::class) + ; + + expect(fn () => $service->invalidReturnConcreteModelCollection()) + ->toThrow(TypePHPTypeError::class, 'covariant ' . TherapistModelFixture::class) + ; + }); +}); From f209bff47f7c76fe4bbb8f90c88965bd9cc301a0 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 11:59:01 +0800 Subject: [PATCH 03/15] Enhance type checking for key-of and value-of generics; add comprehensive tests for template bounds and validation --- src/Internal/Checker/ParamChecker.php | 35 +- src/Internal/Checker/ReturnChecker.php | 3 +- src/Internal/Diagnostic/ErrorFactory.php | 1 + src/Internal/Generics/TemplateManager.php | 363 ++++++++++++++++++ src/Internal/Generics/TemplateSubstitutor.php | 76 ++++ src/Internal/Validator/GenericValidator.php | 58 ++- .../Generics/KeyOfTemplateBoundTest.php | 303 +++++++++++++++ 7 files changed, 833 insertions(+), 6 deletions(-) create mode 100644 tests/TypeChecking/Generics/KeyOfTemplateBoundTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 800ffb2d..a32f762f 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -357,17 +357,39 @@ public static function checkParams( private static function refineInferredTypeFromBound(mixed $val, TypeNode $bound, TypeNode $defaultInferred): TypeNode { + if ($bound instanceof NullableTypeNode) { + if ($val === null) { + return new IdentifierTypeNode('null'); + } + + return self::refineInferredTypeFromBound($val, $bound->type, $defaultInferred); + } + + if ($bound instanceof GenericTypeNode) { + $base = strtolower((string) $bound->type); + if ($base === 'key-of' || $base === 'value-of') { + $expanded = TemplateManager::expandKeyOrValueOf($bound); + if ($expanded !== null) { + return self::refineInferredTypeFromBound($val, $expanded, $defaultInferred); + } + } + } + if ($bound instanceof \PHPStan\PhpDocParser\Ast\Type\ConstTypeNode) { $expectedVal = match (true) { $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode => $bound->constExpr->value, $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode => (int) $bound->constExpr->value, + $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode => (float) $bound->constExpr->value, $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode => true, $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode => false, $bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode => null, default => null, }; - if ($expectedVal !== null && $val === $expectedVal) { + if ( + ($bound->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode && $val === null) + || ($expectedVal !== null && $val === $expectedVal) + ) { return $bound; } } @@ -2985,10 +3007,21 @@ private static function bindInitialTemplate( private static function typeContainsConst(TypeNode $node): bool { + if ($node instanceof NullableTypeNode) { + return self::typeContainsConst($node->type); + } + if ($node instanceof \PHPStan\PhpDocParser\Ast\Type\ConstTypeNode) { return true; } + if ($node instanceof GenericTypeNode) { + $base = strtolower((string) $node->type); + if ($base === 'key-of' || $base === 'value-of') { + return true; + } + } + if ($node instanceof UnionTypeNode) { foreach ($node->types as $member) { if (self::typeContainsConst($member)) { diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index 9ffd9eb3..3f548c97 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -8,6 +8,7 @@ use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use Traversable; use TypePHP\Internal\Diagnostic\ErrorFactory; @@ -511,7 +512,7 @@ private static function evaluateReturn( : $boundTemplates; $fallbackMeta = self::collectUnboundReturnArgIndices($resolvedType, $concreteBound, $templates); $subType = TemplateSubstitutor::substitute($resolvedType, $boundTemplates, $templates); - $resolvedType = $isDynamicReturn + $resolvedType = ($isDynamicReturn || $subType instanceof OffsetAccessTypeNode) ? SpecialTypeResolver::resolve($subType, $function, $thisObj) : $subType; } diff --git a/src/Internal/Diagnostic/ErrorFactory.php b/src/Internal/Diagnostic/ErrorFactory.php index bf0148b0..7694058d 100644 --- a/src/Internal/Diagnostic/ErrorFactory.php +++ b/src/Internal/Diagnostic/ErrorFactory.php @@ -20,6 +20,7 @@ final class ErrorFactory private const CALL_SITE_KEYWORDS = [ 'argument $', 'argument #', + '(): generic type argument ', 'callback ', 'iterator $', 'return iterator', diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 5bf55152..edd9ada2 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -4,8 +4,12 @@ namespace TypePHP\Internal\Generics; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode; @@ -59,6 +63,13 @@ final class TemplateManager */ private static ?WeakMap $fallbackBoundTemplates = null; + /** + * Memoized expansions of key-of<...> and value-of<...> GenericTypeNodes. + * + * @var WeakMap|null + */ + private static ?WeakMap $expandedKeyOrValueOfCache = null; + /** * Call stack frames storing template bindings per function or method call. * @@ -689,6 +700,7 @@ public static function reset(): void self::$compiledBindPlanBySigCache = []; self::$propagatedPropTypeCache = []; self::$fallbackBoundTemplates = null; + self::$expandedKeyOrValueOfCache = null; } /** @@ -3027,6 +3039,327 @@ private static function collectDocsForClassHierarchyMember(\ReflectionClass $hie return $docs; } + /** + * Expands a `key-of` or `value-of` GenericTypeNode into its equivalent concrete TypeNode + * (e.g. literal union for array shapes/enums/constants, key/value type for generic arrays/lists). + */ + public static function expandKeyOrValueOf(GenericTypeNode $node): ?TypeNode + { + self::$expandedKeyOrValueOfCache ??= new WeakMap(); + if (isset(self::$expandedKeyOrValueOfCache[$node])) { + $cached = self::$expandedKeyOrValueOfCache[$node]; + + return $cached !== false ? $cached : null; + } + + $base = strtolower((string) $node->type); + $target = $node->genericTypes[0] ?? null; + + if ($target === null || ($base !== 'key-of' && $base !== 'value-of')) { + self::$expandedKeyOrValueOfCache[$node] = false; + + return null; + } + + $expanded = $base === 'key-of' + ? self::expandKeyOfTarget($target) + : self::expandValueOfTarget($target); + + self::$expandedKeyOrValueOfCache[$node] = $expanded ?? false; + + return $expanded; + } + + private static function expandKeyOfTarget(TypeNode $target): ?TypeNode + { + while ($target instanceof NullableTypeNode) { + $target = $target->type; + } + + if ($target instanceof UnionTypeNode) { + $parts = []; + foreach ($target->types as $member) { + $sub = self::expandKeyOfTarget($member); + if ($sub === null) { + return null; + } + $parts[] = $sub; + } + + return $parts !== [] ? TemplateSubstitutor::normalizeUnion($parts) : null; + } + + if ($target instanceof ArrayShapeNode) { + $keys = []; + $autoIdx = 0; + + foreach ($target->items as $item) { + $key = self::extractShapeKey($item, $autoIdx); + $keys[] = \is_int($key) + ? new ConstTypeNode(new ConstExprIntegerNode((string) $key)) + : new ConstTypeNode(new ConstExprStringNode($key, ConstExprStringNode::SINGLE_QUOTED)); + } + + if (! $target->sealed) { + if ($target->unsealedType !== null && $target->unsealedType->keyType !== null) { + $keys[] = $target->unsealedType->keyType; + } else { + $keys[] = $target->kind === ArrayShapeNode::KIND_LIST + ? (self::$intNode ??= new IdentifierTypeNode('int')) + : new IdentifierTypeNode('array-key'); + } + } + + return $keys !== [] ? TemplateSubstitutor::normalizeUnion($keys) : new IdentifierTypeNode('never'); + } + + if ($target instanceof GenericTypeNode) { + $base = strtolower((string) $target->type); + + if ($base === 'value-of') { + $innerExpanded = self::expandKeyOrValueOf($target); + + return $innerExpanded !== null ? self::expandKeyOfTarget($innerExpanded) : null; + } + + if ($base === 'list' || $base === 'non-empty-list' || $base === 'non-empty-array-list') { + return self::$intNode ??= new IdentifierTypeNode('int'); + } + + if (\in_array($base, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator'], true)) { + return \count($target->genericTypes) >= 2 + ? $target->genericTypes[0] + : new IdentifierTypeNode('array-key'); + } + + return null; + } + + if ($target instanceof ArrayTypeNode) { + return new IdentifierTypeNode('array-key'); + } + + if ($target instanceof IdentifierTypeNode) { + $name = $target->name; + $lower = strtolower($name); + + if ($lower === 'list' || $lower === 'non-empty-list') { + return self::$intNode ??= new IdentifierTypeNode('int'); + } + + if (\in_array($lower, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator', 'mixed'], true)) { + return new IdentifierTypeNode('array-key'); + } + + if (str_contains($name, '::')) { + [$fqcn, $constName] = explode('::', $name, 2); + + return self::expandConstantArrayKeys($fqcn, $constName); + } + + if (ClassNameValidator::isValid($name) && enum_exists($name) && is_subclass_of($name, \UnitEnum::class)) { + $keys = []; + foreach ($name::cases() as $case) { + $keys[] = new ConstTypeNode(new ConstExprStringNode($case->name, ConstExprStringNode::SINGLE_QUOTED)); + } + + return $keys !== [] ? TemplateSubstitutor::normalizeUnion($keys) : new IdentifierTypeNode('never'); + } + + if (\defined($name)) { + return self::expandConstantArrayKeys('', $name); + } + + return null; + } + + if ($target instanceof ConstTypeNode && $target->constExpr instanceof ConstFetchNode) { + return self::expandConstantArrayKeys($target->constExpr->className, $target->constExpr->name); + } + + return null; + } + + private static function expandValueOfTarget(TypeNode $target): ?TypeNode + { + while ($target instanceof NullableTypeNode) { + $target = $target->type; + } + + if ($target instanceof UnionTypeNode) { + $parts = []; + foreach ($target->types as $member) { + $sub = self::expandValueOfTarget($member); + if ($sub === null) { + return null; + } + $parts[] = $sub; + } + + return $parts !== [] ? TemplateSubstitutor::normalizeUnion($parts) : null; + } + + if ($target instanceof ArrayShapeNode) { + $values = []; + foreach ($target->items as $item) { + $values[] = $item->valueType; + } + + if (! $target->sealed) { + $values[] = $target->unsealedType !== null + ? $target->unsealedType->valueType + : (self::$mixedNode ??= new IdentifierTypeNode('mixed')); + } + + return $values !== [] ? TemplateSubstitutor::normalizeUnion($values) : new IdentifierTypeNode('never'); + } + + if ($target instanceof GenericTypeNode) { + $base = strtolower((string) $target->type); + + if ($base === 'list' || $base === 'non-empty-list' || $base === 'non-empty-array-list') { + return $target->genericTypes[0] ?? (self::$mixedNode ??= new IdentifierTypeNode('mixed')); + } + + if (\in_array($base, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator'], true)) { + $count = \count($target->genericTypes); + if ($count >= 2) { + return $target->genericTypes[1]; + } + if ($count === 1) { + return $target->genericTypes[0]; + } + + return self::$mixedNode ??= new IdentifierTypeNode('mixed'); + } + + return null; + } + + if ($target instanceof ArrayTypeNode) { + return $target->type; + } + + if ($target instanceof IdentifierTypeNode) { + $name = $target->name; + $lower = strtolower($name); + + if (\in_array($lower, ['array', 'non-empty-array', 'list', 'non-empty-list', 'iterable', 'traversable', 'generator', 'iterator', 'mixed'], true)) { + return self::$mixedNode ??= new IdentifierTypeNode('mixed'); + } + + if (str_contains($name, '::')) { + [$fqcn, $constName] = explode('::', $name, 2); + + return self::expandConstantArrayValues($fqcn, $constName); + } + + if (ClassNameValidator::isValid($name) && enum_exists($name) && is_subclass_of($name, \BackedEnum::class)) { + $values = []; + foreach ($name::cases() as $case) { + $values[] = \is_int($case->value) + ? new ConstTypeNode(new ConstExprIntegerNode((string) $case->value)) + : new ConstTypeNode(new ConstExprStringNode($case->value, ConstExprStringNode::SINGLE_QUOTED)); + } + + return $values !== [] ? TemplateSubstitutor::normalizeUnion($values) : new IdentifierTypeNode('never'); + } + + if (\defined($name)) { + return self::expandConstantArrayValues('', $name); + } + + return null; + } + + if ($target instanceof ConstTypeNode && $target->constExpr instanceof ConstFetchNode) { + return self::expandConstantArrayValues($target->constExpr->className, $target->constExpr->name); + } + + return null; + } + + private static function expandConstantArrayKeys(string $fqcn, string $constName): ?TypeNode + { + $constValue = self::resolveRawConstantValue($fqcn, $constName); + if (! \is_array($constValue)) { + return null; + } + + $keys = []; + foreach (array_keys($constValue) as $k) { + $keys[] = \is_int($k) + ? new ConstTypeNode(new ConstExprIntegerNode((string) $k)) + : new ConstTypeNode(new ConstExprStringNode($k, ConstExprStringNode::SINGLE_QUOTED)); + } + + return $keys !== [] ? TemplateSubstitutor::normalizeUnion($keys) : new IdentifierTypeNode('never'); + } + + private static function expandConstantArrayValues(string $fqcn, string $constName): ?TypeNode + { + $constValue = self::resolveRawConstantValue($fqcn, $constName); + if (! \is_array($constValue)) { + return null; + } + + $values = []; + foreach ($constValue as $v) { + $values[] = match (true) { + \is_string($v) => new ConstTypeNode(new ConstExprStringNode($v, ConstExprStringNode::SINGLE_QUOTED)), + \is_int($v) => new ConstTypeNode(new ConstExprIntegerNode((string) $v)), + \is_float($v) => new ConstTypeNode(new ConstExprFloatNode((string) $v)), + $v === true => new ConstTypeNode(new ConstExprTrueNode()), + $v === false => new ConstTypeNode(new ConstExprFalseNode()), + $v === null => new ConstTypeNode(new ConstExprNullNode()), + default => self::inferTypeFromValue($v), + }; + } + + return $values !== [] ? TemplateSubstitutor::normalizeUnion($values) : new IdentifierTypeNode('never'); + } + + private static function resolveRawConstantValue(string $fqcn, string $constName): mixed + { + try { + if ($fqcn !== '') { + if (ClassNameValidator::isValid($fqcn) && (class_exists($fqcn) || interface_exists($fqcn) || enum_exists($fqcn))) { + /** @var class-string $fqcn */ + $refClass = new \ReflectionClass($fqcn); + if ($refClass->hasConstant($constName)) { + return $refClass->getConstant($constName); + } + } + + return null; + } + + return \defined($constName) ? \constant($constName) : null; + } catch (\Throwable) { + return null; + } + } + + private static function extractLiteralConstValue(ConstTypeNode $node, bool &$ok): mixed + { + $expr = $node->constExpr; + $ok = true; + + return match (true) { + $expr instanceof ConstExprStringNode => $expr->value, + $expr instanceof ConstExprIntegerNode => (int) $expr->value, + $expr instanceof ConstExprFloatNode => (float) $expr->value, + $expr instanceof ConstExprTrueNode => true, + $expr instanceof ConstExprFalseNode => false, + $expr instanceof ConstExprNullNode => null, + default => (static function () use (&$ok): null { + $ok = false; + + return null; + })(), + }; + } + /** * Recursively checks if an existing type node satisfies an expected type node under a given variance modifier. */ @@ -3078,6 +3411,36 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return false; } + if ($expected instanceof GenericTypeNode) { + $baseExpected = strtolower((string) $expected->type); + if ($baseExpected === 'key-of' || $baseExpected === 'value-of') { + $expandedExpected = self::expandKeyOrValueOf($expected); + if ($expandedExpected !== null) { + return self::checkVariance($existing, $expandedExpected, $variance); + } + } + } + + if ($existing instanceof GenericTypeNode) { + $baseExisting = strtolower((string) $existing->type); + if ($baseExisting === 'key-of' || $baseExisting === 'value-of') { + $expandedExisting = self::expandKeyOrValueOf($existing); + if ($expandedExisting !== null) { + return self::checkVariance($expandedExisting, $expected, $variance); + } + } + } + + if ($existing instanceof ConstTypeNode && $expected instanceof ConstTypeNode) { + $ok1 = false; + $ok2 = false; + $val1 = self::extractLiteralConstValue($existing, $ok1); + $val2 = self::extractLiteralConstValue($expected, $ok2); + if ($ok1 && $ok2) { + return $val1 === $val2; + } + } + if ($variance === GenericTypeNode::VARIANCE_INVARIANT && $existing::class === $expected::class) { if ((string) $existing === (string) $expected) { return true; diff --git a/src/Internal/Generics/TemplateSubstitutor.php b/src/Internal/Generics/TemplateSubstitutor.php index 021ed8ba..217dfbad 100644 --- a/src/Internal/Generics/TemplateSubstitutor.php +++ b/src/Internal/Generics/TemplateSubstitutor.php @@ -4,6 +4,8 @@ namespace TypePHP\Internal\Generics; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; @@ -13,12 +15,14 @@ use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode; use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode; use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; +use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; @@ -214,6 +218,10 @@ private static function substituteNode( return self::substituteObjectShape($node, $boundTemplates, $declaredTemplates, $visited); } + if ($node instanceof OffsetAccessTypeNode) { + return self::substituteOffsetAccess($node, $boundTemplates, $declaredTemplates, $visited); + } + return $node; } @@ -420,4 +428,72 @@ private static function substituteObjectShape( return new ObjectShapeNode($newItems); } + + /** + * @param array $boundTemplates + * @param array $declaredTemplates + * @param array $visited + */ + private static function substituteOffsetAccess( + OffsetAccessTypeNode $node, + array $boundTemplates, + array $declaredTemplates, + array $visited + ): TypeNode { + $baseType = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); + $offsetType = self::substituteNode($node->offset, $boundTemplates, $declaredTemplates, $visited); + + if ($baseType instanceof ArrayShapeNode) { + $offsetKey = null; + if ($offsetType instanceof ConstTypeNode) { + if ($offsetType->constExpr instanceof ConstExprStringNode) { + $offsetKey = $offsetType->constExpr->value; + } elseif ($offsetType->constExpr instanceof ConstExprIntegerNode) { + $offsetKey = (int) $offsetType->constExpr->value; + } + } elseif ($offsetType instanceof IdentifierTypeNode) { + $offsetKey = $offsetType->name; + } + + if ($offsetKey !== null) { + $autoIdx = 0; + foreach ($baseType->items as $item) { + $itemKey = match (true) { + $item->keyName instanceof ConstExprStringNode => $item->keyName->value, + $item->keyName instanceof ConstExprIntegerNode => (int) $item->keyName->value, + $item->keyName instanceof IdentifierTypeNode => $item->keyName->name, + default => $autoIdx, + }; + + if (\is_int($itemKey)) { + $autoIdx = max($autoIdx, $itemKey + 1); + } + + if ($itemKey === $offsetKey) { + return $item->valueType; + } + } + + if ($baseType->unsealedType !== null) { + return $baseType->unsealedType->valueType; + } + } + } elseif ($baseType instanceof GenericTypeNode) { + $baseName = strtolower((string) $baseType->type); + if (\in_array($baseName, ['list', 'non-empty-list', 'non-empty-array-list'], true)) { + return $baseType->genericTypes[0] ?? new IdentifierTypeNode('mixed'); + } + if (\in_array($baseName, ['array', 'non-empty-array', 'iterable'], true)) { + return $baseType->genericTypes[1] ?? $baseType->genericTypes[0] ?? new IdentifierTypeNode('mixed'); + } + } elseif ($baseType instanceof ArrayTypeNode) { + return $baseType->type; + } + + if ($baseType === $node->type && $offsetType === $node->offset) { + return $node; + } + + return new OffsetAccessTypeNode($baseType, $offsetType); + } } diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index ed9c1888..7d106e83 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -10,6 +10,7 @@ use PHPStan\PhpDocParser\Ast\Node as PhpDocNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; @@ -660,12 +661,40 @@ private function validateKeyOf(mixed $value, GenericTypeNode $node, string $cont return null; } - if ($targetType instanceof GenericTypeNode && strtolower((string) $targetType->type) === 'value-of') { - return $this->validateKeyOfNestedValueOf($value, $targetType, $context, $isSensitive); + if ($targetType instanceof GenericTypeNode) { + $innerBase = strtolower((string) $targetType->type); + if ($innerBase === 'value-of') { + return $this->validateKeyOfNestedValueOf($value, $targetType, $context, $isSensitive); + } + + if ($innerBase === 'list' || $innerBase === 'non-empty-list' || $innerBase === 'non-empty-array-list') { + return $registry->validate($value, new IdentifierTypeNode('int'), $context, $isSensitive); + } + + if (\in_array($innerBase, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator'], true)) { + $keyType = \count($targetType->genericTypes) >= 2 + ? $targetType->genericTypes[0] + : new IdentifierTypeNode('array-key'); + + return $registry->validate($value, $keyType, $context, $isSensitive); + } } - if ($targetType instanceof IdentifierTypeNode && ClassNameValidator::isValid($targetType->name) && enum_exists($targetType->name)) { - return $this->validateKeyOfEnum($value, $targetType->name, $context, $isSensitive); + if ($targetType instanceof ArrayTypeNode) { + return $registry->validate($value, new IdentifierTypeNode('array-key'), $context, $isSensitive); + } + + if ($targetType instanceof IdentifierTypeNode) { + $lower = strtolower($targetType->name); + if ($lower === 'list' || $lower === 'non-empty-list') { + return $registry->validate($value, new IdentifierTypeNode('int'), $context, $isSensitive); + } + if (\in_array($lower, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator'], true)) { + return $registry->validate($value, new IdentifierTypeNode('array-key'), $context, $isSensitive); + } + if (ClassNameValidator::isValid($targetType->name) && enum_exists($targetType->name)) { + return $this->validateKeyOfEnum($value, $targetType->name, $context, $isSensitive); + } } if ($targetType instanceof ArrayShapeNode) { @@ -779,6 +808,27 @@ private function validateValueOf(mixed $value, GenericTypeNode $node, string $co return null; } + if ($targetType instanceof GenericTypeNode) { + $innerBase = strtolower((string) $targetType->type); + if ($innerBase === 'list' || $innerBase === 'non-empty-list' || $innerBase === 'non-empty-array-list') { + $valType = $targetType->genericTypes[0] ?? null; + + return $valType !== null ? $registry->validate($value, $valType, $context, $isSensitive) : null; + } + + if (\in_array($innerBase, ['array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator'], true)) { + $valType = \count($targetType->genericTypes) >= 2 + ? $targetType->genericTypes[1] + : ($targetType->genericTypes[0] ?? null); + + return $valType !== null ? $registry->validate($value, $valType, $context, $isSensitive) : null; + } + } + + if ($targetType instanceof ArrayTypeNode) { + return $registry->validate($value, $targetType->type, $context, $isSensitive); + } + if ($targetType instanceof IdentifierTypeNode && ClassNameValidator::isValid($targetType->name) && enum_exists($targetType->name)) { return $this->validateValueOfEnum($value, $targetType->name, $context, $isSensitive); } diff --git a/tests/TypeChecking/Generics/KeyOfTemplateBoundTest.php b/tests/TypeChecking/Generics/KeyOfTemplateBoundTest.php new file mode 100644 index 00000000..14711a8e --- /dev/null +++ b/tests/TypeChecking/Generics/KeyOfTemplateBoundTest.php @@ -0,0 +1,303 @@ + + */ +abstract class KeyOfBoundBase +{ + /** + * @template K of key-of + * + * @param K $key + */ + public function get(string $key): string + { + return $key; + } + + /** + * @template K of key-of + * + * @param K $key + * + * @return K + */ + public function echoKey(string $key, ?string $overrideReturn = null): string + { + return $overrideReturn ?? $key; + } + + /** + * @template K of key-of + * + * @param K|null $key + */ + public function getConfiguration(string $type, ?string $key = null): ?string + { + return $key; + } + + /** + * @template K of key-of + * + * @param K $key + * + * @return T[K] + */ + public function getFieldValue(string $key, mixed $value): mixed + { + return $value; + } + + /** + * @template K of key-of + * + * @param K $key + */ + public function getByAnyKey(int|string $key): int|string + { + return $key; + } + + /** + * @template V of value-of + * + * @param V $value + */ + public function acceptValue(mixed $value): mixed + { + return $value; + } +} + +/** + * @extends KeyOfBoundBase + */ +final class KeyOfBoundChild extends KeyOfBoundBase +{ +} + +/** + * @extends KeyOfBoundBase + */ +final class KeyOfBoundMixedShapeChild extends KeyOfBoundBase +{ +} + +/** + * @extends KeyOfBoundBase + */ +final class KeyOfBoundIntShapeChild extends KeyOfBoundBase +{ +} + +/** + * @extends KeyOfBoundBase> + */ +final class KeyOfBoundStringMapChild extends KeyOfBoundBase +{ +} + +/** + * @extends KeyOfBoundBase> + */ +final class KeyOfBoundIntMapChild extends KeyOfBoundBase +{ +} + +/** + * @extends KeyOfBoundBase + */ +final class KeyOfBoundLiteralValuesChild extends KeyOfBoundBase +{ +} + +enum KeyOfBoundStatus: string +{ + case Active = 'active'; + case Archived = 'archived'; +} + +/** + * @template E of BackedEnum + */ +abstract class KeyOfBoundEnumBase +{ + /** + * @template K of key-of + * + * @param K $caseName + */ + public function byCaseName(string $caseName): string + { + return $caseName; + } + + /** + * @template V of value-of + * + * @param V $caseValue + */ + public function byCaseValue(string $caseValue): string + { + return $caseValue; + } +} + +/** + * @extends KeyOfBoundEnumBase + */ +final class KeyOfBoundStatusRepo extends KeyOfBoundEnumBase +{ +} + +/** + * @template T of array + * @template K of key-of + * + * @param T $data + * @param K $key + */ +function keyOfBoundPick(array $data, string $key): mixed +{ + return $data[$key] ?? null; +} + +describe('Cross-Referenced key-of and value-of Template Bounds (Issue #139)', function () { + describe('1. Method template K of key-of on @extends array shape', function () { + test('accepts valid keys of the array shape bound to T', function () { + $child = new KeyOfBoundChild(); + + expect($child->get('selectedMenu'))->toBe('selectedMenu'); + expect($child->get('readList'))->toBe('readList'); + }); + + test('rejects keys not present in the array shape bound to T', function () { + $child = new KeyOfBoundChild(); + + expect(fn () => $child->get('unknownKey')) + ->toThrow(TypeError::class, 'Argument $key') + ; + }); + + test('infers K as the literal key rather than widening to string', function () { + $child = new KeyOfBoundChild(); + + expect($child->echoKey('selectedMenu'))->toBe('selectedMenu'); + + expect(fn () => $child->echoKey('selectedMenu', 'readList')) + ->toThrow(TypeError::class, 'Return value') + ; + }); + }); + + describe('2. Nullable K|null parameter (getConfiguration pattern)', function () { + test('accepts null and valid keys', function () { + $child = new KeyOfBoundChild(); + + expect($child->getConfiguration('menu', null))->toBeNull(); + expect($child->getConfiguration('menu', 'selectedMenu'))->toBe('selectedMenu'); + expect($child->getConfiguration('menu', 'readList'))->toBe('readList'); + }); + + test('rejects invalid non-null keys', function () { + $child = new KeyOfBoundChild(); + + expect(fn () => $child->getConfiguration('menu', 'nonExistent')) + ->toThrow(TypeError::class, 'Argument $key') + ; + }); + }); + + describe('3. Offset access return type (@return T[K])', function () { + test('validates return value against the specific field type T[K]', function () { + $child = new KeyOfBoundMixedShapeChild(); + + expect($child->getFieldValue('id', 42))->toBe(42); + expect($child->getFieldValue('name', 'Alice'))->toBe('Alice'); + expect($child->getFieldValue('enabled', true))->toBeTrue(); + }); + + test('rejects return value that mismatches T[K] for the passed literal key', function () { + $child = new KeyOfBoundMixedShapeChild(); + + expect(fn () => $child->getFieldValue('id', 'not-an-int')) + ->toThrow(TypeError::class, 'Return value') + ; + + expect(fn () => $child->getFieldValue('name', 123)) + ->toThrow(TypeError::class, 'Return value') + ; + }); + }); + + describe('4. Integer-keyed shapes, generic array maps, and standalone functions', function () { + test('handles integer literal keys in array shapes', function () { + $child = new KeyOfBoundIntShapeChild(); + + expect($child->getByAnyKey(10))->toBe(10); + expect($child->getByAnyKey(20))->toBe(20); + + expect(fn () => $child->getByAnyKey(30)) + ->toThrow(TypeError::class, 'Argument $key') + ; + }); + + test('handles key-of>', function () { + $child = new KeyOfBoundStringMapChild(); + + expect($child->get('anyStringKey'))->toBe('anyStringKey'); + }); + + test('handles key-of>', function () { + $child = new KeyOfBoundIntMapChild(); + + expect($child->getByAnyKey(0))->toBe(0); + expect($child->getByAnyKey(99))->toBe(99); + + expect(fn () => $child->getByAnyKey('wrong')) + ->toThrow(TypeError::class, 'Argument $key') + ; + }); + + test('handles standalone function with @template T and @template K of key-of', function () { + expect(keyOfBoundPick(['a' => 1, 'b' => 2], 'a'))->toBe(1); + }); + }); + + describe('5. value-of and BackedEnum key-of / value-of bounds', function () { + test('handles @template V of value-of on literal-valued array shape', function () { + $child = new KeyOfBoundLiteralValuesChild(); + + expect($child->acceptValue('red'))->toBe('red'); + expect($child->acceptValue('blue'))->toBe('blue'); + + expect(fn () => $child->acceptValue('green')) + ->toThrow(TypeError::class, 'Argument $value') + ; + }); + + test('handles @template K of key-of and @template V of value-of on BackedEnum', function () { + $repo = new KeyOfBoundStatusRepo(); + + expect($repo->byCaseName('Active'))->toBe('Active'); + expect($repo->byCaseName('Archived'))->toBe('Archived'); + expect(fn () => $repo->byCaseName('Deleted')) + ->toThrow(TypeError::class, 'Argument $caseName') + ; + + expect($repo->byCaseValue('active'))->toBe('active'); + expect($repo->byCaseValue('archived'))->toBe('archived'); + expect(fn () => $repo->byCaseValue('deleted')) + ->toThrow(TypeError::class, 'Argument $caseValue') + ; + }); + }); +}); From 3e53cb52dd228abcded2c70157c6c788a1be04d0 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 12:50:22 +0800 Subject: [PATCH 04/15] Refactor ContractVisitor and FunctionContractInjector to improve inline variable handling; add ReturnVarDoubleWrappingTest for comprehensive coverage --- src/Internal/Ast/ContractVisitor.php | 13 +- src/Internal/Ast/FunctionContractInjector.php | 154 ++++++++-- .../Ast/ReturnVarDoubleWrappingTest.php | 289 ++++++++++++++++++ 3 files changed, 431 insertions(+), 25 deletions(-) create mode 100644 tests/Internal/Ast/ReturnVarDoubleWrappingTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 5e9a41da..c247a506 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -287,13 +287,6 @@ public function enterNode(Node $node): Node|array|null $this->processClassPropertyDefaults($node); } - if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) { - $classContext = $this->classStack !== [] ? end($this->classStack) : null; - FunctionContractInjector::inject($node, $classContext, $this->currentFile, $this->currentNamespace); - - return null; - } - if ($node instanceof Node\Stmt\Property) { PropertyHookInjector::process($node); @@ -356,6 +349,11 @@ public function enterNode(Node $node): Node|array|null */ public function leaveNode(Node $node): Node|array|null { + if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) { + $classContext = $this->classStack !== [] ? end($this->classStack) : null; + FunctionContractInjector::inject($node, $classContext, $this->currentFile, $this->currentNamespace); + } + $this->trackDeclarationExit($node); if ($node instanceof Node\Stmt\Unset_) { @@ -1749,6 +1747,7 @@ private function handleReturn(Node\Stmt\Return_ $node): void $node->getStartLine() ); $node->setAttribute('typephp_var_wrapped', true); + $node->setAttribute('typephp_var_type', $typeString); } } diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 9f22ddc3..ae33abe4 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -22,12 +22,15 @@ use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use PHPStan\PhpDocParser\Parser\TokenIterator; use TypePHP\Internal\Ast\Elimination\EliminationSafetyPolicy; use TypePHP\Internal\Ast\Elimination\Evaluator\GeneratorEvaluator; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Docblock\DocblockExtractor; +use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StubManager; @@ -260,7 +263,8 @@ public static function inject( $hasParam, $trustedParamTypes, $useDynamicMethodKey, - $currentNamespace + $currentNamespace, + $effectiveAliases ) : self::wrapNonGeneratorReturns( $node->stmts, @@ -278,7 +282,8 @@ public static function inject( $trustedParamTypes, $useDynamicMethodKey, ! $isMagicGet && ! $isMagicCall, - $currentNamespace + $currentNamespace, + $effectiveAliases ); } @@ -624,6 +629,22 @@ public function enterNode(Node $node): ?int } } } elseif ($node instanceof Node\Expr\CallLike) { + if ( + $node instanceof Node\Expr\FuncCall + && $node->name instanceof Node\Name + && str_starts_with(ltrim($node->name->toString(), '\\'), 'TypePHP\\Internal\\RuntimeTypeChecker::') + ) { + return null; + } + + if ( + $node instanceof Node\Expr\StaticCall + && $node->class instanceof Node\Name + && ltrim($node->class->toString(), '\\') === 'TypePHP\\Internal\\RuntimeTypeChecker' + ) { + return null; + } + if ( $node instanceof Node\Expr\FuncCall && $node->name instanceof Node\Name @@ -1672,11 +1693,79 @@ public static function buildWrappedYieldNode( ); } + /** + * Determines whether a Return_ node already wrapped by ContractVisitor::handleReturn() + * safely subsumes the enclosing function/generator return contract. + * + * @param array $effectiveAliases + */ + public static function inlineVarSubsumesReturn( + Node\Stmt\Return_ $returnNode, + ?TypeNode $targetReturnType, + bool $isEliminationSafe, + array $effectiveAliases = [], + string $currentFile = '', + ?string $currentNamespace = null + ): bool { + if ($returnNode->getAttribute('typephp_var_wrapped') !== true) { + return false; + } + + $varTypeString = $returnNode->getAttribute('typephp_var_type'); + if (! \is_string($varTypeString) || $varTypeString === '') { + return true; + } + + if ( + ! $isEliminationSafe + || $targetReturnType === null + || ! Config::isInlineScalarsEnabled() + || ! Config::isInlineArraysEnabled() + || ! Config::isInlineObjectsEnabled() + || ! Config::isInlineGenericsEnabled() + || ! Config::isInlineCallablesEnabled() + ) { + return false; + } + + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($varTypeString))); + $varTypeNode = $typeParser->parse($tokens); + + if ($effectiveAliases !== []) { + $varTypeNode = DocblockParser::substituteAliases($varTypeNode, $effectiveAliases); + } + + if ($currentFile !== '') { + $varTypeNode = SpecialTypeResolver::resolveForFile($varTypeNode, $currentFile, $currentNamespace, false); + $targetReturnType = SpecialTypeResolver::resolveForFile($targetReturnType, $currentFile, $currentNamespace, false); + } + + if ($varTypeNode instanceof NullableTypeNode) { + $varTypeNode = new UnionTypeNode([$varTypeNode->type, new IdentifierTypeNode('null')]); + } + + if ($targetReturnType instanceof NullableTypeNode) { + $targetReturnType = new UnionTypeNode([$targetReturnType->type, new IdentifierTypeNode('null')]); + } + + return TemplateManager::checkVariance( + $varTypeNode, + $targetReturnType, + GenericTypeNode::VARIANCE_COVARIANT + ); + } catch (\Throwable) { + return false; + } + } + /** * @param array $stmts * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext * @param array $byRefParams * @param array $trustedParamTypes + * @param array $effectiveAliases * * @return array */ @@ -1694,7 +1783,8 @@ private static function wrapGeneratorReturns( bool $hasScope = false, array $trustedParamTypes = [], bool $useDynamicMethodKey = false, - ?string $currentNamespace = null + ?string $currentNamespace = null, + array $effectiveAliases = [] ): array { $canEliminate = $functionNode !== null && ! $hasMethodTemplates @@ -1724,13 +1814,15 @@ private static function wrapGeneratorReturns( $hasSelfOut, $trustedParamTypes, $useDynamicMethodKey, - $currentNamespace + $currentNamespace, + $effectiveAliases ) extends NodeVisitorAbstract { /** * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $explicitGenContract * @param array $byRefParams * @param array $trustedParamTypes + * @param array $effectiveAliases */ public function __construct( private Node\Expr $thisArg, @@ -1742,7 +1834,8 @@ public function __construct( private bool $hasSelfOut, private array $trustedParamTypes, private bool $useDynamicMethodKey, - private ?string $currentNamespace + private ?string $currentNamespace, + private array $effectiveAliases ) { } @@ -1851,7 +1944,7 @@ public function enterNode(Node $n): int|Node|array|null } if ($n instanceof Node\Stmt\Return_) { - if ($n->getAttribute('typephp_var_wrapped') === true || $n->getAttribute('typephp_generator_return_wrapped') === true) { + if ($n->getAttribute('typephp_generator_return_wrapped') === true) { return null; } $n->setAttribute('typephp_generator_return_wrapped', true); @@ -1869,6 +1962,17 @@ public function enterNode(Node $n): int|Node|array|null $exitStmts = [...$exitStmts, ...$paramOutStmts]; } + if (FunctionContractInjector::inlineVarSubsumesReturn( + $n, + $this->genContract['return'] ?? null, + $this->genContract !== null, + $this->effectiveAliases, + $this->currentFile, + $this->currentNamespace + )) { + return $exitStmts !== [] ? [...$exitStmts, $n] : null; + } + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; @@ -1971,6 +2075,7 @@ public function enterNode(Node $n): int|Node|array|null * @param array $byRefParams * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext * @param array $trustedParamTypes + * @param array $effectiveAliases * * @return array */ @@ -1990,7 +2095,8 @@ private static function wrapNonGeneratorReturns( array $trustedParamTypes = [], bool $useDynamicMethodKey = false, bool $canGuardReturnCache = true, - ?string $currentNamespace = null + ?string $currentNamespace = null, + array $effectiveAliases = [] ): array { self::tagPrecedingAssignments($stmts); @@ -2010,12 +2116,14 @@ private static function wrapNonGeneratorReturns( $trustedParamTypes, $useDynamicMethodKey, $canGuardReturnCache, - $currentNamespace + $currentNamespace, + $effectiveAliases ) extends NodeVisitorAbstract { /** * @param array $byRefParams * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext * @param array $trustedParamTypes + * @param array $effectiveAliases */ public function __construct( private Node\Expr $thisArg, @@ -2032,7 +2140,8 @@ public function __construct( private array $trustedParamTypes, private bool $useDynamicMethodKey, private bool $canGuardReturnCache, - private ?string $currentNamespace + private ?string $currentNamespace, + private array $effectiveAliases ) { } @@ -2062,10 +2171,6 @@ public function enterNode(Node $n): int|array|null } if ($n instanceof Node\Stmt\Return_) { - if ($n->getAttribute('typephp_var_wrapped') === true) { - return null; - } - $exitStmts = []; if ($this->hasSelfOut) { $exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars, $this->useDynamicMethodKey); @@ -2083,17 +2188,30 @@ public function enterNode(Node $n): int|array|null return $exitStmts !== [] ? [...$exitStmts, $n] : null; } + $isReturnElimSafe = ! $this->isByRefReturn + && ! $this->isNativeVoid + && $this->functionNode !== null + && $this->returnTypeNode !== null + && EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode); + + if (FunctionContractInjector::inlineVarSubsumesReturn( + $n, + $this->returnTypeNode, + $isReturnElimSafe, + $this->effectiveAliases, + $this->currentFile, + $this->currentNamespace + )) { + return $exitStmts !== [] ? [...$exitStmts, $n] : null; + } + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; if ( - ! $this->isByRefReturn - && ! $this->isNativeVoid - && $this->functionNode !== null - && $this->returnTypeNode !== null - && EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode) + $isReturnElimSafe && StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile, $this->trustedParamTypes, $this->currentNamespace) ) { return $exitStmts !== [] ? [...$exitStmts, $n] : null; diff --git a/tests/Internal/Ast/ReturnVarDoubleWrappingTest.php b/tests/Internal/Ast/ReturnVarDoubleWrappingTest.php new file mode 100644 index 00000000..d78e6bc0 --- /dev/null +++ b/tests/Internal/Ast/ReturnVarDoubleWrappingTest.php @@ -0,0 +1,289 @@ +toContain("RuntimeTypeChecker::checkVariable(\$x, 'positive-int', 'return'") + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ; + }); + + test('enforces named /** @var positive-int $x */ return $x; instead of silently dropping it', function () { + $source = <<<'PHP' +toContain("RuntimeTypeChecker::checkVariable(\$x, 'positive-int', 'x'") + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ; + + $baseTemp = sys_get_temp_dir() . '/typephp_ret_named_var_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + $filePath = $tempDir . '/named_var_return.php'; + file_put_contents($filePath, $source); + + try { + Config::set([ + 'include' => [str_replace('\\', '/', $tempDir) . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $filePath; + + expect(\TypePHP\Tests\Internal\Ast\ReturnVarFixture\returnNamedNarrowerVar(5))->toBe(5); + + expect(fn () => \TypePHP\Tests\Internal\Ast\ReturnVarFixture\returnNamedNarrowerVar(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('still enforces stricter @return contract when inline @var is wider, with checkVariable inside checkReturn', function () { + $source = <<<'PHP' +toContain("RuntimeTypeChecker::checkVariable(\$x, 'int', 'return'") + ->and($varPos)->toBeInt() + ->and($retPos)->toBeInt() + ->and($varPos)->toBeLessThan($retPos) + ; + + $baseTemp = sys_get_temp_dir() . '/typephp_ret_wider_var_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + $filePath = $tempDir . '/wider_var_return.php'; + file_put_contents($filePath, $source); + + try { + Config::set([ + 'include' => [str_replace('\\', '/', $tempDir) . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $filePath; + + expect(\TypePHP\Tests\Internal\Ast\ReturnVarWiderFixture\returnWiderInlineVar(5))->toBe(5); + + expect(fn () => \TypePHP\Tests\Internal\Ast\ReturnVarWiderFixture\returnWiderInlineVar('not-an-int')) + ->toThrow(TypeError::class, 'must be of type int') + ; + + expect(fn () => \TypePHP\Tests\Internal\Ast\ReturnVarWiderFixture\returnWiderInlineVar(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('preserves @param-out checks before /** @var T */ return $x;', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkParamOut') + ->and($transformed)->toContain("RuntimeTypeChecker::checkVariable(\$val, 'positive-int', 'return'") + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ; + + $baseTemp = sys_get_temp_dir() . '/typephp_ret_paramout_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + $filePath = $tempDir . '/param_out_var_return.php'; + file_put_contents($filePath, $source); + + try { + Config::set([ + 'include' => [str_replace('\\', '/', $tempDir) . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $filePath; + + $out = 10; + expect(fn () => \TypePHP\Tests\Internal\Ast\ReturnVarParamOutFixture\returnVarWithParamOut(5, $out)) + ->toThrow(TypeError::class, 'param-out') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('does not double-wrap generator return when /** @var T */ satisfies TReturn', function () { + $source = <<<'PHP' + + */ +function genReturnMatchingVar(mixed $x): \Generator +{ + yield 0 => 'ok'; + + /** @var positive-int */ + return $x; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'gen_return_matching_var.php'); + + expect($transformed)->toContain("RuntimeTypeChecker::checkVariable(\$x, 'positive-int', 'return'") + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkGeneratorReturn') + ; + }); + + test('still enforces inherited interface @return contract when child method uses wider inline @var on return', function () { + $source = <<<'PHP' + [str_replace('\\', '/', $tempDir) . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $filePath; + + $impl = new ReturnVarLspFixture\IdProviderImpl(); + + expect($impl->getId(10))->toBe(10); + + expect(fn () => $impl->getId(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); +}); From 1ea0f4e85270343c523312ef6aa0471f073c7bc1 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 13:02:20 +0800 Subject: [PATCH 05/15] Enhance exception safety in StreamWrapper; add tests to ensure wrapper remains registered during error handling --- src/Internal/Io/StreamWrapper.php | 295 +++++++++++------- .../Io/StreamWrapperExceptionSafetyTest.php | 212 +++++++++++++ 2 files changed, 391 insertions(+), 116 deletions(-) create mode 100644 tests/Internal/Io/StreamWrapperExceptionSafetyTest.php diff --git a/src/Internal/Io/StreamWrapper.php b/src/Internal/Io/StreamWrapper.php index 8d8478c3..6940bf09 100644 --- a/src/Internal/Io/StreamWrapper.php +++ b/src/Internal/Io/StreamWrapper.php @@ -423,79 +423,86 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ return $this->openDirectHandle($path, $mode, $options, $openedPath); } + $wasRegistered = self::$isRegistered; + $missingTarget = null; + $success = false; self::unregister(); - if (! $useIncludePath && isset(self::$realpathCache[$path])) { - $resolvedPath = self::$realpathCache[$path]; - } else { - $resolvedPath = self::silent(static function () use ($path, $useIncludePath): string|false { - $real = realpath($path); - if ($real !== false) { - return $real; - } + try { + if (! $useIncludePath && isset(self::$realpathCache[$path])) { + $resolvedPath = self::$realpathCache[$path]; + } else { + $resolvedPath = self::silent(static function () use ($path, $useIncludePath): string|false { + $real = realpath($path); + if ($real !== false) { + return $real; + } - if ($useIncludePath) { - $resolved = stream_resolve_include_path($path); - if ($resolved !== false) { - $realResolved = realpath($resolved); + if ($useIncludePath) { + $resolved = stream_resolve_include_path($path); + if ($resolved !== false) { + $realResolved = realpath($resolved); - return $realResolved !== false ? $realResolved : $resolved; + return $realResolved !== false ? $realResolved : $resolved; + } } - } - return false; - }); - if (! $useIncludePath && $resolvedPath !== false) { - self::$realpathCache[$path] = $resolvedPath; + return false; + }); + if (! $useIncludePath && $resolvedPath !== false) { + self::$realpathCache[$path] = $resolvedPath; + } } - } - if ($resolvedPath === false || ! self::isApplicationFile($path, $resolvedPath)) { - if (! $useIncludePath && $resolvedPath !== false) { - self::$bypassedPathCache[$path] = true; - } + if ($resolvedPath === false || ! self::isApplicationFile($path, $resolvedPath)) { + if (! $useIncludePath && $resolvedPath !== false) { + self::$bypassedPathCache[$path] = true; + } - $target = ($resolvedPath !== false) ? $resolvedPath : $path; - /** @var resource|false $handle */ - $handle = self::silent( - fn () => ($this->context !== null) - ? fopen($target, $mode, $useIncludePath, $this->context) - : fopen($target, $mode, $useIncludePath) - ); - $this->handle = $handle !== false ? $handle : null; - $this->eof = false; - if ($this->handle !== null) { - if ($resolvedPath !== false) { - $openedPath = $resolvedPath; + $target = ($resolvedPath !== false) ? $resolvedPath : $path; + /** @var resource|false $handle */ + $handle = self::silent( + fn () => ($this->context !== null) + ? fopen($target, $mode, $useIncludePath, $this->context) + : fopen($target, $mode, $useIncludePath) + ); + $this->handle = $handle !== false ? $handle : null; + $this->eof = false; + if ($this->handle !== null) { + if ($resolvedPath !== false) { + $openedPath = $resolvedPath; + } else { + $meta = stream_get_meta_data($this->handle); + if (isset($meta['uri']) && $meta['uri'] !== '') { + $openedPath = $meta['uri']; + } + } + $success = true; } else { - $meta = stream_get_meta_data($this->handle); - if (isset($meta['uri']) && $meta['uri'] !== '') { - $openedPath = $meta['uri']; + $missingTarget = $target; + } + } else { + $success = self::$cacheEnabled + ? $this->openCachedStream($resolvedPath, $mode) + : $this->openMemoryStream($resolvedPath); + + if ($success) { + $openedPath = $resolvedPath; + if (self::shouldTrackTelemetry()) { + self::$instrumentedFiles[$resolvedPath] = true; } } } - self::register(); - - if ($this->handle === null && ! self::isPharCall()) { - trigger_error("include({$target}): Failed to open stream: No such file or directory", E_USER_WARNING); + } finally { + if ($wasRegistered) { + self::register(); } - - return $this->handle !== null; } - $success = self::$cacheEnabled - ? $this->openCachedStream($resolvedPath, $mode) - : $this->openMemoryStream($resolvedPath); - - if ($success) { - $openedPath = $resolvedPath; - if (self::shouldTrackTelemetry()) { - self::$instrumentedFiles[$resolvedPath] = true; - } + if ($missingTarget !== null && ! self::isPharCall()) { + trigger_error("include({$missingTarget}): Failed to open stream: No such file or directory", E_USER_WARNING); } - self::register(); - return $success; } @@ -525,34 +532,41 @@ private function openDirectHandle(string $targetFile, string $mode, int $options $useIncludePath = ($options & STREAM_USE_PATH) !== 0; $isWriteMode = strpbrk($mode, 'waxc+') !== false; + $wasRegistered = self::$isRegistered; self::unregister(); - /** @var resource|false $handle */ - $handle = self::silent( - fn () => ($this->context !== null) - ? fopen($targetFile, $mode, $useIncludePath, $this->context) - : fopen($targetFile, $mode, $useIncludePath) - ); - $this->handle = $handle !== false ? $handle : null; - $this->eof = false; - if ($this->handle !== null) { - if ($useIncludePath || $isInclude) { - $meta = stream_get_meta_data($this->handle); - if (isset($meta['uri']) && $meta['uri'] !== '') { - $openedPath = $meta['uri']; + try { + /** @var resource|false $handle */ + $handle = self::silent( + fn () => ($this->context !== null) + ? fopen($targetFile, $mode, $useIncludePath, $this->context) + : fopen($targetFile, $mode, $useIncludePath) + ); + $this->handle = $handle !== false ? $handle : null; + $this->eof = false; + + if ($this->handle !== null) { + if ($useIncludePath || $isInclude) { + $meta = stream_get_meta_data($this->handle); + if (isset($meta['uri']) && $meta['uri'] !== '') { + $openedPath = $meta['uri']; + } } - } - if ($isWriteMode) { - $this->openedRawPath = $targetFile; - $this->openedNormalizedPath = str_replace('\\', '/', $targetFile); - $resolvedWrite = self::silent(static fn () => realpath($targetFile)); - $this->openedResolvedPath = ($resolvedWrite !== false && $resolvedWrite !== $targetFile) ? $resolvedWrite : null; - $this->wasWritten = true; - $this->invalidateOpenedWritePaths(); + if ($isWriteMode) { + $this->openedRawPath = $targetFile; + $this->openedNormalizedPath = str_replace('\\', '/', $targetFile); + $resolvedWrite = self::silent(static fn () => realpath($targetFile)); + $this->openedResolvedPath = ($resolvedWrite !== false && $resolvedWrite !== $targetFile) ? $resolvedWrite : null; + $this->wasWritten = true; + $this->invalidateOpenedWritePaths(); + } + } + } finally { + if ($wasRegistered) { + self::register(); } } - self::register(); if ($this->handle === null && ! self::isPharCall()) { $action = $isInclude ? 'include' : 'fopen'; @@ -757,10 +771,17 @@ public function url_stat(string $path, int $flags): array|false return false; } + $wasRegistered = self::$isRegistered; self::unregister(); - /** @var array|false $result */ - $result = self::silent(static fn () => $isLink ? @lstat($path) : @stat($path)); - self::register(); + + try { + /** @var array|false $result */ + $result = self::silent(static fn () => $isLink ? @lstat($path) : @stat($path)); + } finally { + if ($wasRegistered) { + self::register(); + } + } if ($result !== false) { $isPhp = str_ends_with($normalized, '.php') || str_ends_with(strtolower($normalized), '.php'); @@ -791,35 +812,49 @@ public function stream_metadata(string $path, int $option, mixed $value): bool self::$bypassedPathCache[$path] ); + $wasRegistered = self::$isRegistered; self::unregister(); - $result = false; - if ($option === STREAM_META_TOUCH) { - /** @var array{0?: int, 1?: int} $valueArray */ - $valueArray = \is_array($value) ? $value : []; - $time = $valueArray[0] ?? time(); - $atime = $valueArray[1] ?? $time; - $result = (bool) self::silent(fn () => @touch($path, (int) $time, (int) $atime)); - } elseif ($option === STREAM_META_ACCESS) { - /** @var int $mode */ - $mode = \is_int($value) ? $value : 0777; - $result = (bool) self::silent(fn () => @chmod($path, $mode)); + + try { + $result = false; + if ($option === STREAM_META_TOUCH) { + /** @var array{0?: int, 1?: int} $valueArray */ + $valueArray = \is_array($value) ? $value : []; + $time = $valueArray[0] ?? time(); + $atime = $valueArray[1] ?? $time; + $result = (bool) self::silent(fn () => @touch($path, (int) $time, (int) $atime)); + } elseif ($option === STREAM_META_ACCESS) { + /** @var int $mode */ + $mode = \is_int($value) ? $value : 0777; + $result = (bool) self::silent(fn () => @chmod($path, $mode)); + } + } finally { + if ($wasRegistered) { + self::register(); + } } - self::register(); return $result; } public function dir_opendir(string $path, int $options): bool { + $wasRegistered = self::$isRegistered; self::unregister(); - /** @var resource|false $dh */ - $dh = self::silent( - fn () => ($this->context !== null) - ? @opendir($path, $this->context) - : @opendir($path) - ); - $this->dirHandle = $dh !== false ? $dh : null; - self::register(); + + try { + /** @var resource|false $dh */ + $dh = self::silent( + fn () => ($this->context !== null) + ? @opendir($path, $this->context) + : @opendir($path) + ); + $this->dirHandle = $dh !== false ? $dh : null; + } finally { + if ($wasRegistered) { + self::register(); + } + } return $this->dirHandle !== null; } @@ -865,11 +900,18 @@ public function mkdir(string $path, int $mode, int $options): bool self::$bypassedPathCache[$path] ); + $wasRegistered = self::$isRegistered; self::unregister(); - $result = ($this->context !== null) - ? @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0, $this->context) - : @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0); - self::register(); + + try { + $result = ($this->context !== null) + ? @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0, $this->context) + : @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0); + } finally { + if ($wasRegistered) { + self::register(); + } + } return $result; } @@ -885,11 +927,18 @@ public function rmdir(string $path, int $options): bool self::$bypassedPathCache[$path] ); + $wasRegistered = self::$isRegistered; self::unregister(); - $result = ($this->context !== null) - ? rmdir($path, $this->context) - : rmdir($path); - self::register(); + + try { + $result = ($this->context !== null) + ? rmdir($path, $this->context) + : rmdir($path); + } finally { + if ($wasRegistered) { + self::register(); + } + } return $result; } @@ -905,11 +954,18 @@ public function unlink(string $path): bool self::$bypassedPathCache[$path] ); + $wasRegistered = self::$isRegistered; self::unregister(); - $result = ($this->context !== null) - ? unlink($path, $this->context) - : unlink($path); - self::register(); + + try { + $result = ($this->context !== null) + ? unlink($path, $this->context) + : unlink($path); + } finally { + if ($wasRegistered) { + self::register(); + } + } return $result; } @@ -931,11 +987,18 @@ public function rename(string $pathFrom, string $pathTo): bool self::$bypassedPathCache[$pathTo] ); + $wasRegistered = self::$isRegistered; self::unregister(); - $result = ($this->context !== null) - ? rename($pathFrom, $pathTo, $this->context) - : rename($pathFrom, $pathTo); - self::register(); + + try { + $result = ($this->context !== null) + ? rename($pathFrom, $pathTo, $this->context) + : rename($pathFrom, $pathTo); + } finally { + if ($wasRegistered) { + self::register(); + } + } return $result; } diff --git a/tests/Internal/Io/StreamWrapperExceptionSafetyTest.php b/tests/Internal/Io/StreamWrapperExceptionSafetyTest.php new file mode 100644 index 00000000..81748d1f --- /dev/null +++ b/tests/Internal/Io/StreamWrapperExceptionSafetyTest.php @@ -0,0 +1,212 @@ +toBeTrue(); + + $caught = false; + + try { + $withThrowingErrorHandler(static function () use ($missingFile): void { + unlink($missingFile); + }); + } catch (ErrorException) { + $caught = true; + } + + expect($caught)->toBeTrue() + ->and(StreamWrapper::isRegistered())->toBeTrue() + ; + }); + + test('keeps file:// wrapper registered when rmdir() throws ErrorException on non-empty directory', function () use ($withThrowingErrorHandler) { + $tempDir = sys_get_temp_dir() . '/typephp_ex_rmdir_' . uniqid(); + mkdir($tempDir, 0777, true); + $childFile = $tempDir . '/keep.txt'; + file_put_contents($childFile, 'data'); + + try { + $caught = false; + + try { + $withThrowingErrorHandler(static function () use ($tempDir): void { + rmdir($tempDir); + }); + } catch (ErrorException) { + $caught = true; + } + + expect($caught)->toBeTrue() + ->and(StreamWrapper::isRegistered())->toBeTrue() + ; + } finally { + StreamWrapper::register(); + @unlink($childFile); + @rmdir($tempDir); + } + }); + + test('keeps file:// wrapper registered when rename() throws ErrorException on missing source', function () use ($withThrowingErrorHandler) { + $missingFrom = sys_get_temp_dir() . '/typephp_ex_rename_from_' . uniqid() . '.tmp'; + $destTo = sys_get_temp_dir() . '/typephp_ex_rename_to_' . uniqid() . '.tmp'; + + $caught = false; + + try { + $withThrowingErrorHandler(static function () use ($missingFrom, $destTo): void { + rename($missingFrom, $destTo); + }); + } catch (ErrorException) { + $caught = true; + } + + expect($caught)->toBeTrue() + ->and(StreamWrapper::isRegistered())->toBeTrue() + ; + }); + + test('keeps file:// wrapper registered when mkdir() throws ErrorException under naive error handler', function () use ($withThrowingErrorHandler) { + $tempDir = sys_get_temp_dir() . '/typephp_ex_mkdir_' . uniqid(); + mkdir($tempDir, 0777, true); + + try { + $caught = false; + + try { + $withThrowingErrorHandler(static function () use ($tempDir): void { + mkdir($tempDir); + }); + } catch (ErrorException) { + $caught = true; + } + + expect($caught)->toBeTrue() + ->and(StreamWrapper::isRegistered())->toBeTrue() + ; + } finally { + StreamWrapper::register(); + @rmdir($tempDir); + } + }); + + test('keeps file:// wrapper registered when stream_open() throws during application file read', function () use ($withThrowingErrorHandler) { + $baseTemp = sys_get_temp_dir() . '/typephp_ex_open_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + $dirNamedPhp = $tempDir . '/broken.php'; + mkdir($dirNamedPhp, 0777, true); + + try { + Config::set([ + 'cache' => false, + 'include' => [str_replace('\\', '/', $tempDir) . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(['cache' => false]); + + $caught = false; + + try { + $withThrowingErrorHandler(static function () use ($dirNamedPhp): void { + include $dirNamedPhp; + }); + } catch (ErrorException) { + $caught = true; + } + + expect($caught)->toBeTrue() + ->and(StreamWrapper::isRegistered())->toBeTrue() + ; + } finally { + StreamWrapper::register(); + @rmdir($dirNamedPhp); + @rmdir($tempDir); + } + }); + + test('continues instrumenting subsequent required files after a caught filesystem ErrorException', function () use ($withThrowingErrorHandler) { + $baseTemp = sys_get_temp_dir() . '/typephp_ex_e2e_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + $scriptPath = $tempDir . '/after_error_service.php'; + $missingFile = $tempDir . '/does_not_exist.tmp'; + + file_put_contents($scriptPath, <<<'PHP' + [str_replace('\\', '/', $tempDir) . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + try { + $withThrowingErrorHandler(static function () use ($missingFile): void { + unlink($missingFile); + }); + } catch (ErrorException) { + } + + require_once $scriptPath; + + expect(\TypePHP\Tests\Internal\Io\ExceptionSafetyFixture\acceptPositiveAfterError(10))->toBe(10); + + expect(fn () => \TypePHP\Tests\Internal\Io\ExceptionSafetyFixture\acceptPositiveAfterError(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + } finally { + StreamWrapper::register(); + @unlink($scriptPath); + @rmdir($tempDir); + } + }); +}); From 5dcc26f319035297773249ab7a56bdcf55b4bce3 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 13:19:35 +0800 Subject: [PATCH 06/15] Refactor import handling in ContractVisitor and StreamWrapper; enhance SpecialTypeResolver to isolate non-class use imports and add comprehensive tests for import collision scenarios --- src/Internal/Ast/ContractVisitor.php | 10 +- src/Internal/Io/StreamWrapper.php | 10 +- src/Internal/Resolver/SpecialTypeResolver.php | 53 +++++--- .../Resolver/SpecialTypeResolverTest.php | 7 +- .../SpecialTypeResolverUseImportsTest.php | 119 ++++++++++++++++++ 5 files changed, 168 insertions(+), 31 deletions(-) create mode 100644 tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index c247a506..bcd33434 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -1654,11 +1654,11 @@ private static function collectNamespaceImports(array $stmts): array } elseif ($stmt instanceof Node\Stmt\GroupUse) { $prefix = $stmt->prefix->toString(); foreach ($stmt->uses as $use) { - if ( - $use->type !== Node\Stmt\Use_::TYPE_NORMAL - && $use->type !== Node\Stmt\Use_::TYPE_UNKNOWN - && $stmt->type !== Node\Stmt\Use_::TYPE_NORMAL - ) { + $effectiveType = $use->type !== Node\Stmt\Use_::TYPE_UNKNOWN + ? $use->type + : $stmt->type; + + if ($effectiveType !== Node\Stmt\Use_::TYPE_NORMAL) { continue; } $imports[$use->getAlias()->toString()] = $prefix . '\\' . $use->name->toString(); diff --git a/src/Internal/Io/StreamWrapper.php b/src/Internal/Io/StreamWrapper.php index 6940bf09..2137a93d 100644 --- a/src/Internal/Io/StreamWrapper.php +++ b/src/Internal/Io/StreamWrapper.php @@ -1247,11 +1247,11 @@ private static function scanNamespaceStatements( $prefix = $stmt->prefix->toString(); foreach ($stmt->uses as $use) { - if ( - $use->type !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL - && $use->type !== \PhpParser\Node\Stmt\Use_::TYPE_UNKNOWN - && $stmt->type !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL - ) { + $effectiveType = $use->type !== \PhpParser\Node\Stmt\Use_::TYPE_UNKNOWN + ? $use->type + : $stmt->type; + + if ($effectiveType !== \PhpParser\Node\Stmt\Use_::TYPE_NORMAL) { continue; } diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 60fddc8f..561a5b6f 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -1745,6 +1745,8 @@ public static function parseFileMetadata(string $fileName, string $source): void } $useStatement = ''; + $isGroupUse = false; + for ($j = $i + 1; $j < $count; $j++) { if ($tokens[$j]->text === ';') { $i = $j; @@ -1752,6 +1754,7 @@ public static function parseFileMetadata(string $fileName, string $source): void break; } if ($tokens[$j]->text === '{') { + $isGroupUse = true; $prefix = trim($useStatement); $groupContent = ''; for ($g = $j + 1; $g < $count; $g++) { @@ -1760,40 +1763,56 @@ public static function parseFileMetadata(string $fileName, string $source): void break; } - $groupContent .= $tokens[$g]->text; - } - foreach (explode(',', $groupContent) as $part) { - $part = trim($part); - if ($part === '') { - continue; + if ($tokens[$g]->id !== T_COMMENT && $tokens[$g]->id !== T_DOC_COMMENT) { + $groupContent .= $tokens[$g]->text; } - if (preg_match('/^([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', $part, $m) === 1) { - $fqcn = ltrim(rtrim($prefix, '\\') . '\\' . trim($m[1]), '\\'); - $alias = $m[2] ?? basename(str_replace('\\', '/', $fqcn)); - $imports[$alias] = $fqcn; - $allImports[$alias] = $fqcn; + } + + if (preg_match('/^(?:function|const)\s+/i', $prefix) !== 1) { + foreach (explode(',', $groupContent) as $part) { + $part = trim($part); + if ($part === '' || preg_match('/^(?:function|const)\s+/i', $part) === 1) { + continue; + } + if (preg_match('/^([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', $part, $m) === 1) { + $fqcn = ltrim(rtrim($prefix, '\\') . '\\' . trim($m[1]), '\\'); + $alias = $m[2] ?? basename(str_replace('\\', '/', $fqcn)); + $imports[$alias] = $fqcn; + $allImports[$alias] = $fqcn; + } } } break; } - $useStatement .= $tokens[$j]->text; + if ($tokens[$j]->id !== T_COMMENT && $tokens[$j]->id !== T_DOC_COMMENT) { + $useStatement .= $tokens[$j]->text; + } + } + + if ($isGroupUse) { + continue; + } + + $trimmedUse = trim($useStatement); + if ($trimmedUse === '' || preg_match('/^(?:function|const)\s+/i', $trimmedUse) === 1) { + continue; } - if (str_contains($useStatement, ',')) { - foreach (explode(',', $useStatement) as $part) { + if (str_contains($trimmedUse, ',')) { + foreach (explode(',', $trimmedUse) as $part) { $part = trim($part); - if ($part === '') { + if ($part === '' || preg_match('/^(?:function|const)\s+/i', $part) === 1) { continue; } - if (preg_match('/^(?:function\s+|const\s+)?([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', $part, $m) === 1) { + if (preg_match('/^([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', $part, $m) === 1) { $fqcn = ltrim(trim($m[1]), '\\'); $alias = $m[2] ?? basename(str_replace('\\', '/', $fqcn)); $imports[$alias] = $fqcn; $allImports[$alias] = $fqcn; } } - } elseif (preg_match('/^(?:function\s+|const\s+)?([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', trim($useStatement), $m) === 1) { + } elseif (preg_match('/^([a-zA-Z0-9_\\\\]+)(?:\s+as\s+([a-zA-Z0-9_]+))?$/i', $trimmedUse, $m) === 1) { $fqcn = ltrim(trim($m[1]), '\\'); $alias = $m[2] ?? basename(str_replace('\\', '/', $fqcn)); $imports[$alias] = $fqcn; diff --git a/tests/Internal/Resolver/SpecialTypeResolverTest.php b/tests/Internal/Resolver/SpecialTypeResolverTest.php index e5392fa1..4434b8f1 100644 --- a/tests/Internal/Resolver/SpecialTypeResolverTest.php +++ b/tests/Internal/Resolver/SpecialTypeResolverTest.php @@ -357,10 +357,9 @@ public function process(): void ->and($imports['Str'])->toBe('App\Helpers\StringHelper') ; - expect($imports)->toHaveKey('compute') - ->and($imports['compute'])->toBe('App\Utils\calculateTotal') - ->and($imports)->toHaveKey('LIMIT') - ->and($imports['LIMIT'])->toBe('App\Config\MAX_ITEMS') + expect($imports)->not()->toHaveKey('compute') + ->and($imports)->not()->toHaveKey('LIMIT') + ->and($imports)->not()->toHaveKey('Contracts') ; expect($imports)->not()->toHaveKey('userData') diff --git a/tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php b/tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php new file mode 100644 index 00000000..93877e4a --- /dev/null +++ b/tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php @@ -0,0 +1,119 @@ +toBe([ + 'User' => 'App\Models\User', + 'CustomerOrder' => 'App\Models\Order', + 'PaymentInterface' => 'App\Contracts\PaymentInterface', + 'Refund' => 'App\Contracts\RefundInterface', + ]) + ->and($imports)->not()->toHaveKey('Contracts') + ->and($imports)->not()->toHaveKey('helperFn') + ->and($imports)->not()->toHaveKey('MAX_RETRIES') + ->and($imports)->not()->toHaveKey('compute') + ->and($imports)->not()->toHaveKey('formatA') + ->and($imports)->not()->toHaveKey('fmtB') + ->and($imports)->not()->toHaveKey('fnOne') + ->and($imports)->not()->toHaveKey('fn2') + ->and($imports)->not()->toHaveKey('LIMIT') + ->and($imports)->not()->toHaveKey('FLAG_A') + ->and($imports)->not()->toHaveKey('FB') + ->and($imports)->not()->toHaveKey('CONST_ONE') + ->and($imports)->not()->toHaveKey('C2') + ; + }); + + test('resolveFqcnForFile resolves same-namespace class instead of colliding use function / use const import', function () { + $source = <<<'PHP' +toBe(UseImportCollisionTarget::class) + ; + }); + + test('StreamWrapper AST metadata seeding ignores group use function and use const imports', function () { + $source = <<<'PHP' +toBe([ + 'User' => 'App\Models\User', + ]); + }); +}); From 804a22a4a1b4b57f56ded41d94e914717361bcae Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 14:01:36 +0800 Subject: [PATCH 07/15] Refactor Config class to improve environment variable handling; add tests for RuntimeTypeChecker synchronization with TYPEPHP_DISABLE and TYPEPHP_ENABLED --- src/Internal/Util/Config.php | 51 +++++++++++++++++------------- tests/Internal/Util/ConfigTest.php | 39 +++++++++++++++++++++++ 2 files changed, 68 insertions(+), 22 deletions(-) diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index 0fe1558e..00d3edd2 100644 --- a/src/Internal/Util/Config.php +++ b/src/Internal/Util/Config.php @@ -138,44 +138,51 @@ private static function getEnvValue(string $key): ?string return null; } - public static function isEnabled(): bool + private static function isDisabledByEnvOrConst(): bool { if (! self::$processEnvProbed) { self::probeProcessEnvOverrides(); } if ( - self::$hasProcessEnvOverride - || isset($_ENV['TYPEPHP_DISABLE']) - || isset($_SERVER['TYPEPHP_DISABLE']) - || isset($_ENV['TYPEPHP_ENABLED']) - || isset($_SERVER['TYPEPHP_ENABLED']) - || \defined('TYPEPHP_DISABLE') + ! self::$hasProcessEnvOverride + && ! isset($_ENV['TYPEPHP_DISABLE']) + && ! isset($_SERVER['TYPEPHP_DISABLE']) + && ! isset($_ENV['TYPEPHP_ENABLED']) + && ! isset($_SERVER['TYPEPHP_ENABLED']) + && ! \defined('TYPEPHP_DISABLE') ) { - $envDisable = self::resolveEnabledOverride('TYPEPHP_DISABLE', self::$processEnvDisable); - if ($envDisable !== null && trim($envDisable) !== '') { - if (filter_var($envDisable, FILTER_VALIDATE_BOOLEAN)) { - return false; - } - } + return false; + } - $envEnabled = self::resolveEnabledOverride('TYPEPHP_ENABLED', self::$processEnvEnabled); - if ($envEnabled !== null && trim($envEnabled) !== '') { - if (! filter_var($envEnabled, FILTER_VALIDATE_BOOLEAN)) { - return false; - } + $envDisable = self::resolveEnabledOverride('TYPEPHP_DISABLE', self::$processEnvDisable); + if ($envDisable !== null && trim($envDisable) !== '') { + if (filter_var($envDisable, FILTER_VALIDATE_BOOLEAN)) { + return true; } + } - if (\defined('TYPEPHP_DISABLE') && (bool) TYPEPHP_DISABLE) { - return false; + $envEnabled = self::resolveEnabledOverride('TYPEPHP_ENABLED', self::$processEnvEnabled); + if ($envEnabled !== null && trim($envEnabled) !== '') { + if (! filter_var($envEnabled, FILTER_VALIDATE_BOOLEAN)) { + return true; } } + return \defined('TYPEPHP_DISABLE') && (bool) TYPEPHP_DISABLE; + } + + public static function isEnabled(): bool + { + if (self::isDisabledByEnvOrConst()) { + return RuntimeTypeChecker::$isEnabled = false; + } + if (self::$cachedConfig === null) { self::get(); } - return self::$enabled; + return RuntimeTypeChecker::$isEnabled = self::$enabled; } public static function isEliminateStaticallyProvenChecksEnabled(): bool @@ -961,7 +968,7 @@ private static function syncFlags(array $config): void self::$inlineArrays = (bool) ($inline['arrays'] ?? true); self::$inlineObjects = (bool) ($inline['objects'] ?? true); - RuntimeTypeChecker::$isEnabled = self::$enabled; + RuntimeTypeChecker::$isEnabled = self::$enabled && ! self::isDisabledByEnvOrConst(); RuntimeTypeChecker::$paramsEnabled = self::$params; RuntimeTypeChecker::$returnsEnabled = self::$returns; RuntimeTypeChecker::$paramsOutEnabled = self::$params && self::$paramsOut; diff --git a/tests/Internal/Util/ConfigTest.php b/tests/Internal/Util/ConfigTest.php index 9d21128b..2145b794 100644 --- a/tests/Internal/Util/ConfigTest.php +++ b/tests/Internal/Util/ConfigTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +use TypePHP\Internal\Diagnostic\ErrorMessage; +use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\Config; function cleanTypePhpEnvVariables(): void @@ -410,6 +412,43 @@ function cleanTypePhpEnvVariables(): void unset($_SERVER['TYPEPHP_REDACT_VALUES']); }); + + test('syncs RuntimeTypeChecker::$isEnabled when TYPEPHP_DISABLE or TYPEPHP_ENABLED is set before Config::get() / Config::set()', function () { + $_ENV['TYPEPHP_DISABLE'] = 'true'; + Config::reset(); + + Config::get(); + + expect(RuntimeTypeChecker::$isEnabled)->toBeFalse() + ->and(RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'age', __FILE__))->toBe(-5) + ; + + unset($_ENV['TYPEPHP_DISABLE']); + $_ENV['TYPEPHP_ENABLED'] = 'false'; + + Config::set(['enabled' => true]); + + expect(RuntimeTypeChecker::$isEnabled)->toBeFalse() + ->and(RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'age', __FILE__))->toBe(-5) + ; + }); + + test('syncs RuntimeTypeChecker::$isEnabled when Config::isEnabled() observes Dotenv changes after boot', function () { + Config::get(); + expect(RuntimeTypeChecker::$isEnabled)->toBeTrue(); + + $_ENV['TYPEPHP_DISABLE'] = 'true'; + expect(Config::isEnabled())->toBeFalse() + ->and(RuntimeTypeChecker::$isEnabled)->toBeFalse() + ->and(RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'age', __FILE__))->toBe(-5) + ; + + $_ENV['TYPEPHP_DISABLE'] = 'false'; + expect(Config::isEnabled())->toBeTrue() + ->and(RuntimeTypeChecker::$isEnabled)->toBeTrue() + ->and(RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'age', __FILE__))->toBeInstanceOf(ErrorMessage::class) + ; + }); }); describe('Composer.json Extra Configuration Integration', function () { From 7c183afde254bd0e80370461b874d189187163c6 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 14:24:52 +0800 Subject: [PATCH 08/15] Add reset method to ObjectShapeValidator and invoke it in TypeValidatorRegistry reset --- src/Internal/RuntimeTypeChecker.php | 5 +++-- src/Internal/Validator/ObjectShapeValidator.php | 6 ++++++ src/Internal/Validator/TypeValidatorRegistry.php | 1 + 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index c586bdb6..d4eb1d2b 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -2666,9 +2666,10 @@ private static function compileSimpleReturnOp(TypeNode $resolvedType): array } $name = $inner->name; + $lower = strtolower($name); if ($isNullable) { - $nullableOp = match ($name) { + $nullableOp = match ($lower) { 'int', 'integer' => self::PARAM_CHECK_NULL_OR_INT, 'string' => self::PARAM_CHECK_NULL_OR_STRING, 'bool', 'boolean' => self::PARAM_CHECK_NULL_OR_BOOL, @@ -2680,7 +2681,7 @@ private static function compileSimpleReturnOp(TypeNode $resolvedType): array } } - $op = match ($name) { + $op = match ($lower) { 'int', 'integer' => self::PARAM_CHECK_INT, 'string' => self::PARAM_CHECK_STRING, 'bool', 'boolean' => self::PARAM_CHECK_BOOL, diff --git a/src/Internal/Validator/ObjectShapeValidator.php b/src/Internal/Validator/ObjectShapeValidator.php index 76a78d3f..740d6cd4 100644 --- a/src/Internal/Validator/ObjectShapeValidator.php +++ b/src/Internal/Validator/ObjectShapeValidator.php @@ -33,6 +33,12 @@ final class ObjectShapeValidator implements TypeValidatorInterface */ private static array $propertyCache = []; + public static function reset(): void + { + self::$refClassCache = []; + self::$propertyCache = []; + } + public function validate( mixed $value, TypeNode $node, diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index 5a6503ec..707e2df7 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -47,6 +47,7 @@ public static function reset(): void { GenericValidator::reset(); ArrayShapeValidator::reset(); + ObjectShapeValidator::reset(); ConstValidator::reset(); } From 2bd18c528ab6c7a0ee1302ab6eb61258ed23feaf Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 15:52:55 +0800 Subject: [PATCH 09/15] Refactor RuntimeTypeChecker to replace MemberAssignChecker constants with class-specific constants for improved performance --- src/Internal/RuntimeTypeChecker.php | 174 +++++++++++++++++----------- 1 file changed, 106 insertions(+), 68 deletions(-) diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index d4eb1d2b..fb66ce6b 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -101,6 +101,44 @@ final class RuntimeTypeChecker private const PARAM_CHECK_INT_OR_FLOAT = 26; + private const PROP_OP_NONE = 0; + + private const PROP_OP_INT = 1; + + private const PROP_OP_STRING = 2; + + private const PROP_OP_BOOL = 3; + + private const PROP_OP_FLOAT = 4; + + private const PROP_OP_POSITIVE_INT = 5; + + private const PROP_OP_NON_EMPTY_STRING = 6; + + private const PROP_OP_ARRAY_KEY = 7; + + private const PROP_OP_ARRAY = 8; + + private const PROP_OP_OBJECT = 9; + + private const PROP_OP_CLASS = 10; + + private const PROP_OP_MASK = 11; + + private const PROP_BIT_INT = 1; + + private const PROP_BIT_STRING = 2; + + private const PROP_BIT_BOOL = 4; + + private const PROP_BIT_FLOAT = 8; + + private const PROP_BIT_OBJECT = 16; + + private const PROP_BIT_NULL = 32; + + private const PROP_BIT_ARRAY = 64; + public static bool $isEnabled = true; public static bool $paramsEnabled = true; @@ -461,54 +499,54 @@ public static function checkPropertyMemberAssign( if (! $c[0] || $key === null) { $keyOk = true; - if (! $c[0] && $key !== null && $c[1] !== MemberAssignChecker::OP_NONE) { + if (! $c[0] && $key !== null && $c[1] !== self::PROP_OP_NONE) { $kExtra = $c[2]; $keyOk = match ($c[1]) { - MemberAssignChecker::OP_INT => \is_int($key), - MemberAssignChecker::OP_STRING => \is_string($key), - MemberAssignChecker::OP_ARRAY_KEY => \is_int($key) || \is_string($key), - MemberAssignChecker::OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', - MemberAssignChecker::OP_POSITIVE_INT => \is_int($key) && $key > 0, - MemberAssignChecker::OP_MASK => \is_int($kExtra) && ( - (\is_string($key) && ($kExtra & MemberAssignChecker::BIT_STRING) !== 0) - || (\is_int($key) && ($kExtra & (MemberAssignChecker::BIT_INT | MemberAssignChecker::BIT_FLOAT)) !== 0) - || (\is_object($key) && ($kExtra & MemberAssignChecker::BIT_OBJECT) !== 0) - || (\is_bool($key) && ($kExtra & MemberAssignChecker::BIT_BOOL) !== 0) - || (\is_float($key) && ($kExtra & MemberAssignChecker::BIT_FLOAT) !== 0) - || (\is_array($key) && ($kExtra & MemberAssignChecker::BIT_ARRAY) !== 0) + self::PROP_OP_INT => \is_int($key), + self::PROP_OP_STRING => \is_string($key), + self::PROP_OP_ARRAY_KEY => \is_int($key) || \is_string($key), + self::PROP_OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', + self::PROP_OP_POSITIVE_INT => \is_int($key) && $key > 0, + self::PROP_OP_MASK => \is_int($kExtra) && ( + (\is_string($key) && ($kExtra & self::PROP_BIT_STRING) !== 0) + || (\is_int($key) && ($kExtra & (self::PROP_BIT_INT | self::PROP_BIT_FLOAT)) !== 0) + || (\is_object($key) && ($kExtra & self::PROP_BIT_OBJECT) !== 0) + || (\is_bool($key) && ($kExtra & self::PROP_BIT_BOOL) !== 0) + || (\is_float($key) && ($kExtra & self::PROP_BIT_FLOAT) !== 0) + || (\is_array($key) && ($kExtra & self::PROP_BIT_ARRAY) !== 0) ), - MemberAssignChecker::OP_OBJECT => \is_object($key), - MemberAssignChecker::OP_CLASS => \is_object($key) && \is_string($kExtra) && ($key instanceof $kExtra), + self::PROP_OP_OBJECT => \is_object($key), + self::PROP_OP_CLASS => \is_object($key) && \is_string($kExtra) && ($key instanceof $kExtra), default => false, }; } if ($keyOk) { $vOp = $c[3]; - if ($vOp === MemberAssignChecker::OP_NONE) { + if ($vOp === self::PROP_OP_NONE) { return $value; } $vExtra = $c[4]; $valOk = match ($vOp) { - MemberAssignChecker::OP_INT => \is_int($value), - MemberAssignChecker::OP_STRING => \is_string($value), - MemberAssignChecker::OP_BOOL => \is_bool($value), - MemberAssignChecker::OP_FLOAT => \is_float($value) || \is_int($value), - MemberAssignChecker::OP_POSITIVE_INT => \is_int($value) && $value > 0, - MemberAssignChecker::OP_NON_EMPTY_STRING => \is_string($value) && $value !== '', - MemberAssignChecker::OP_ARRAY_KEY => \is_int($value) || \is_string($value), - MemberAssignChecker::OP_ARRAY => \is_array($value), - MemberAssignChecker::OP_OBJECT => \is_object($value), - MemberAssignChecker::OP_CLASS => \is_object($value) && \is_string($vExtra) && ($value instanceof $vExtra), - MemberAssignChecker::OP_MASK => \is_int($vExtra) && ( - (\is_string($value) && ($vExtra & MemberAssignChecker::BIT_STRING) !== 0) - || (\is_int($value) && ($vExtra & (MemberAssignChecker::BIT_INT | MemberAssignChecker::BIT_FLOAT)) !== 0) - || (\is_object($value) && ($vExtra & MemberAssignChecker::BIT_OBJECT) !== 0) - || (\is_bool($value) && ($vExtra & MemberAssignChecker::BIT_BOOL) !== 0) - || (\is_float($value) && ($vExtra & MemberAssignChecker::BIT_FLOAT) !== 0) - || ($value === null && ($vExtra & MemberAssignChecker::BIT_NULL) !== 0) - || (\is_array($value) && ($vExtra & MemberAssignChecker::BIT_ARRAY) !== 0) + self::PROP_OP_INT => \is_int($value), + self::PROP_OP_STRING => \is_string($value), + self::PROP_OP_BOOL => \is_bool($value), + self::PROP_OP_FLOAT => \is_float($value) || \is_int($value), + self::PROP_OP_POSITIVE_INT => \is_int($value) && $value > 0, + self::PROP_OP_NON_EMPTY_STRING => \is_string($value) && $value !== '', + self::PROP_OP_ARRAY_KEY => \is_int($value) || \is_string($value), + self::PROP_OP_ARRAY => \is_array($value), + self::PROP_OP_OBJECT => \is_object($value), + self::PROP_OP_CLASS => \is_object($value) && \is_string($vExtra) && ($value instanceof $vExtra), + self::PROP_OP_MASK => \is_int($vExtra) && ( + (\is_string($value) && ($vExtra & self::PROP_BIT_STRING) !== 0) + || (\is_int($value) && ($vExtra & (self::PROP_BIT_INT | self::PROP_BIT_FLOAT)) !== 0) + || (\is_object($value) && ($vExtra & self::PROP_BIT_OBJECT) !== 0) + || (\is_bool($value) && ($vExtra & self::PROP_BIT_BOOL) !== 0) + || (\is_float($value) && ($vExtra & self::PROP_BIT_FLOAT) !== 0) + || ($value === null && ($vExtra & self::PROP_BIT_NULL) !== 0) + || (\is_array($value) && ($vExtra & self::PROP_BIT_ARRAY) !== 0) ), default => false, }; @@ -711,54 +749,54 @@ public static function checkPropertyDimAssign( if (! $c[0] || $key === null) { $keyOk = true; - if (! $c[0] && $key !== null && $c[1] !== MemberAssignChecker::OP_NONE) { + if (! $c[0] && $key !== null && $c[1] !== self::PROP_OP_NONE) { $kExtra = $c[2]; $keyOk = match ($c[1]) { - MemberAssignChecker::OP_INT => \is_int($key), - MemberAssignChecker::OP_STRING => \is_string($key), - MemberAssignChecker::OP_ARRAY_KEY => \is_int($key) || \is_string($key), - MemberAssignChecker::OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', - MemberAssignChecker::OP_POSITIVE_INT => \is_int($key) && $key > 0, - MemberAssignChecker::OP_MASK => \is_int($kExtra) && ( - (\is_string($key) && ($kExtra & MemberAssignChecker::BIT_STRING) !== 0) - || (\is_int($key) && ($kExtra & (MemberAssignChecker::BIT_INT | MemberAssignChecker::BIT_FLOAT)) !== 0) - || (\is_object($key) && ($kExtra & MemberAssignChecker::BIT_OBJECT) !== 0) - || (\is_bool($key) && ($kExtra & MemberAssignChecker::BIT_BOOL) !== 0) - || (\is_float($key) && ($kExtra & MemberAssignChecker::BIT_FLOAT) !== 0) - || (\is_array($key) && ($kExtra & MemberAssignChecker::BIT_ARRAY) !== 0) + self::PROP_OP_INT => \is_int($key), + self::PROP_OP_STRING => \is_string($key), + self::PROP_OP_ARRAY_KEY => \is_int($key) || \is_string($key), + self::PROP_OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', + self::PROP_OP_POSITIVE_INT => \is_int($key) && $key > 0, + self::PROP_OP_MASK => \is_int($kExtra) && ( + (\is_string($key) && ($kExtra & self::PROP_BIT_STRING) !== 0) + || (\is_int($key) && ($kExtra & (self::PROP_BIT_INT | self::PROP_BIT_FLOAT)) !== 0) + || (\is_object($key) && ($kExtra & self::PROP_BIT_OBJECT) !== 0) + || (\is_bool($key) && ($kExtra & self::PROP_BIT_BOOL) !== 0) + || (\is_float($key) && ($kExtra & self::PROP_BIT_FLOAT) !== 0) + || (\is_array($key) && ($kExtra & self::PROP_BIT_ARRAY) !== 0) ), - MemberAssignChecker::OP_OBJECT => \is_object($key), - MemberAssignChecker::OP_CLASS => \is_object($key) && \is_string($kExtra) && ($key instanceof $kExtra), + self::PROP_OP_OBJECT => \is_object($key), + self::PROP_OP_CLASS => \is_object($key) && \is_string($kExtra) && ($key instanceof $kExtra), default => false, }; } if ($keyOk) { $vOp = $c[3]; - if ($vOp === MemberAssignChecker::OP_NONE) { + if ($vOp === self::PROP_OP_NONE) { return $value; } $vExtra = $c[4]; $valOk = match ($vOp) { - MemberAssignChecker::OP_INT => \is_int($value), - MemberAssignChecker::OP_STRING => \is_string($value), - MemberAssignChecker::OP_BOOL => \is_bool($value), - MemberAssignChecker::OP_FLOAT => \is_float($value) || \is_int($value), - MemberAssignChecker::OP_POSITIVE_INT => \is_int($value) && $value > 0, - MemberAssignChecker::OP_NON_EMPTY_STRING => \is_string($value) && $value !== '', - MemberAssignChecker::OP_ARRAY_KEY => \is_int($value) || \is_string($value), - MemberAssignChecker::OP_ARRAY => \is_array($value), - MemberAssignChecker::OP_OBJECT => \is_object($value), - MemberAssignChecker::OP_CLASS => \is_object($value) && \is_string($vExtra) && ($value instanceof $vExtra), - MemberAssignChecker::OP_MASK => \is_int($vExtra) && ( - (\is_string($value) && ($vExtra & MemberAssignChecker::BIT_STRING) !== 0) - || (\is_int($value) && ($vExtra & (MemberAssignChecker::BIT_INT | MemberAssignChecker::BIT_FLOAT)) !== 0) - || (\is_object($value) && ($vExtra & MemberAssignChecker::BIT_OBJECT) !== 0) - || (\is_bool($value) && ($vExtra & MemberAssignChecker::BIT_BOOL) !== 0) - || (\is_float($value) && ($vExtra & MemberAssignChecker::BIT_FLOAT) !== 0) - || ($value === null && ($vExtra & MemberAssignChecker::BIT_NULL) !== 0) - || (\is_array($value) && ($vExtra & MemberAssignChecker::BIT_ARRAY) !== 0) + self::PROP_OP_INT => \is_int($value), + self::PROP_OP_STRING => \is_string($value), + self::PROP_OP_BOOL => \is_bool($value), + self::PROP_OP_FLOAT => \is_float($value) || \is_int($value), + self::PROP_OP_POSITIVE_INT => \is_int($value) && $value > 0, + self::PROP_OP_NON_EMPTY_STRING => \is_string($value) && $value !== '', + self::PROP_OP_ARRAY_KEY => \is_int($value) || \is_string($value), + self::PROP_OP_ARRAY => \is_array($value), + self::PROP_OP_OBJECT => \is_object($value), + self::PROP_OP_CLASS => \is_object($value) && \is_string($vExtra) && ($value instanceof $vExtra), + self::PROP_OP_MASK => \is_int($vExtra) && ( + (\is_string($value) && ($vExtra & self::PROP_BIT_STRING) !== 0) + || (\is_int($value) && ($vExtra & (self::PROP_BIT_INT | self::PROP_BIT_FLOAT)) !== 0) + || (\is_object($value) && ($vExtra & self::PROP_BIT_OBJECT) !== 0) + || (\is_bool($value) && ($vExtra & self::PROP_BIT_BOOL) !== 0) + || (\is_float($value) && ($vExtra & self::PROP_BIT_FLOAT) !== 0) + || ($value === null && ($vExtra & self::PROP_BIT_NULL) !== 0) + || (\is_array($value) && ($vExtra & self::PROP_BIT_ARRAY) !== 0) ), default => false, }; From 9aeaee7aefca92ac53d1d8082eebf22e25b94e99 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 16:45:51 +0800 Subject: [PATCH 10/15] Enhance internal documentation for type checkers and template manager; detail performance optimizations and architectural considerations --- src/Internal/Checker/GeneratorChecker.php | 20 ++++++++++++- src/Internal/Checker/InlineChecker.php | 17 ++++++++++- src/Internal/Checker/MemberAssignChecker.php | 24 ++++++++++++++- src/Internal/Checker/ParamChecker.php | 23 ++++++++++++++- src/Internal/Checker/ReturnChecker.php | 18 +++++++++++- src/Internal/Generics/TemplateManager.php | 26 +++++++++++++++- src/Internal/RuntimeTypeChecker.php | 31 +++++++++++++++++++- 7 files changed, 152 insertions(+), 7 deletions(-) diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index 9c93ddca..9f08b15f 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -22,7 +22,25 @@ use WeakMap; /** - * @internal Evaluates generator yield, send (TSend), and return (TReturn) type validations. + * Evaluates generator `yield` (TKey/TValue), `$gen->send()` (TSend), and `return` (TReturn) + * type validations at runtime. + * + * Performance & Mechanical Sympathy Architecture: + * `checkYield()` executes on every yielded element in a generator loop. To keep per-yield + * overhead near-native: + * + * - Local `private const` opcodes and primitive bitmasks (`OP_*`, `BIT_*`) are intentionally + * kept class-local and matched inline inside `checkYield()` so PHP compiles an O(1) + * `ZEND_MATCH` jump table and bypasses `TypeValidatorRegistry` dispatch for common types. + * - Compiled yield/send/return tuples are cached directly on the active `ScopeCleaner::$resolvedYieldTypes` + * handle (zero-lookup on subsequent yields in the same generator), backed by static, + * template-signature, and `WeakMap` per-instance caches (`$noContractCache`, + * `$generatorPlanCache`, `$staticYieldTypeCache`, `$genericYieldTypeCache`, `$instanceYieldCache`). + * + * Contributor note: Do not replace local `private const` opcodes with cross-class constants or + * extract the inline `match` dispatch into a helper without benchmarking tight generator loops. + * + * @internal */ final class GeneratorChecker { diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index f34299f9..2b2f7aa7 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -36,7 +36,22 @@ use TypePHP\Internal\Wrapper\CallableWrapper; /** - * Evaluates inline variable (@var) and class property validation rules. + * Evaluates inline variable (`@var`), class property, and single-element collection mutation + * validation contracts at runtime. + * + * Performance & Mechanical Sympathy Architecture: + * Inline property and local variable checks can fire inside tight loops. Overhead is minimized via: + * + * - Shared O(1) negative property cache (`$nullPropertyCache`) checked directly by + * `RuntimeTypeChecker` and `MemberAssignChecker` so unannotated properties bail out on a single + * `isset()` before entering `InlineChecker`. + * - Pre-classified AST parse cache (`$parsedTypeNodeCache` storing `[$typeNode, $needsContext]`), + * 3D file/class context caches (`$resolvedFileTypeCache`, `$resolvedClassContextCache`), + * static/instance generic property caches (`$resolvedStaticPropertyTypeCache`, + * `$instancePropertyTypeCache` WeakMap), and O(1) lookup tables (`SCALAR_TYPES`, `ARRAY_TYPES`) + * to skip context resolution and reflection when types are self-contained. + * - O(1) leaf element validation (`validateCollectionElementMutation()`) in hybrid mode to avoid + * full-collection copies on single-element writes. * * @internal */ diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 103cec2d..7b25b3a5 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -32,7 +32,29 @@ use WeakMap; /** - * @internal Evaluates array key/dimension and object shape property member assignments. + * Evaluates array dimension, collection element, and object shape property member assignments + * and `unset()` mutations atomically before writing. + * + * Performance & Mechanical Sympathy Architecture: + * Collection and property-dimension writes (`$this->items[] = $v`, `$this->map[$k] = $v`) are + * among the hottest mutation paths in collection-heavy workloads. This class avoids copy-on-write + * full-array validation (`StructureMutator::mutateCopy()`) whenever possible via: + * + * - Packed per-instance fast contracts (`$fastObjectContractCache` WeakMap) shared directly with + * `RuntimeTypeChecker::checkPropertyDimAssign()` and `checkPropertyMemberAssign()` for O(1) + * 1-level writes without array allocation. + * - Inline `match` blocks over integer opcodes and primitive bitmasks (`OP_*`, `BIT_*`), compiled + * by PHP into O(1) `ZEND_MATCH` jump tables and compile-time folded bitmasks across both + * 1-level and 2-level nested property-dimension writes. + * - Multi-tier memoization (`$propertyMutationPlanCache`, `$substitutedElementContractCache`, + * `$instanceContractCache`, `$innerElementContractCache`, `$arrayAccessPlanCache`, + * `$refPropertyCache`) so reflection and template substitution run once per class/binding shape. + * + * Contributor note: `OP_*` and `BIT_*` values are mirrored as local `private const`s in + * `RuntimeTypeChecker::PROP_OP_*` / `PROP_BIT_*` to preserve compile-time `ZEND_MATCH` jump + * tables across both files — keep them strictly synchronized if modified. + * + * @internal */ final class MemberAssignChecker { diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index a32f762f..effc08ba 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -32,9 +32,30 @@ use TypePHP\Internal\Validator\TypeValidatorRegistry; /** + * Evaluates function and method parameter contracts, generic template inference, and dynamic + * `@method` calls routed through `__call` / `__callStatic`. + * + * Performance & Mechanical Sympathy Architecture: + * Executed on parameter-validated calls that do not hit `RuntimeTypeChecker`'s compiled + * monomorphic fast-path plans. To maximize throughput on generic and polymorphic workloads: + * + * - Inline scalar/collection `match` fast path inside `validateSimpleParams()` bypasses + * `TypeValidatorRegistry` dispatch for common primitive and refinement identifiers. + * - Bitmask-gated pre-inference (`$preInferMaskCache`) skips closure, array, shape, and generic + * object inference passes when the function signature cannot benefit from them, and + * single-pass array inference self-verifies plain `array<...>`/`iterable<...>` arguments + * (`$selfVerifiedParams`) to avoid scanning elements twice. + * - Primitive bitmask bound plans (`$templateBoundPlanCache`) and multi-dimensional caches + * (`$noParamContractCache`, `$effectiveFunctionCache`, `$baseTypeCache`, + * `$substitutedParamCache`, `$callableNodesCache`, `$traversablePlanCache`, `$functionKindCache`) + * avoid repeated reflection, AST substitution, and string key allocations. + * + * Contributor note: Keep the inline primitive `match` in `validateSimpleParams()` and bitmask + * guards intact when adding new parameter features. + * * @phpstan-import-type FunctionContract from DocblockParser * - * @internal Evaluates function and method parameter contract validations (including dynamic @method calls via __call / __callStatic). + * @internal */ final class ParamChecker { diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index 3f548c97..b0f61079 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -21,9 +21,25 @@ use TypePHP\Internal\Wrapper\CallableWrapper; /** + * Evaluates function and method return contracts, including dynamic `@method` returns + * (`__call` / `__callStatic`) and dynamic `@property` reads (`__get`). + * + * Performance & Mechanical Sympathy Architecture: + * Serves the fallback path for generic, aliased, conditional, dynamic (`$this`/`static`), + * and magic return contracts not handled by `RuntimeTypeChecker::$simpleReturnPlanCache`: + * + * - Fast-exit checks handle `$this` identity, `static` instanceof, and unconstrained + * (`mixed`/`array`) returns before allocating template binding arrays or running substitution. + * - Direct `$topCallFrame` and `TemplateManager::getInstanceBindingsFast()` lookups avoid full + * binding merges when a method uses only class-level or only method-level templates. + * - Multi-tier AST resolution caches (`$noReturnContractCache`, `$resolvedStaticReturnCache`, + * `$unboundReturnCache`, `$substitutedReturnCache`, `$substitutedConditionalReturnCache`) + * memoize substituted return types by compact template signatures to avoid repeated + * `TemplateSubstitutor` and `SpecialTypeResolver` traversals. + * * @phpstan-import-type FunctionContract from DocblockParser * - * @internal Evaluates function and method return contract validations (including dynamic @method calls via __call / __callStatic and dynamic @property reads via __get). + * @internal */ final class ReturnChecker { diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index edd9ada2..b3bcc83b 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -42,7 +42,31 @@ use WeakMap; /** - * Manages generic template bindings for object instances (via WeakMap) and static/method call stack frames. + * Manages reified generic template bindings for object instances (via WeakMap) + * and active function/method call stack frames, along with variance and inheritance resolution. + * + * Performance & Mechanical Sympathy Architecture: + * Generic binding and variance checks run frequently across constructor, parameter, property, + * and return boundaries. This class minimizes allocations and reflection overhead via: + * + * - GC-safe `WeakMap` instance storage (`$instanceTemplateBindings`, `$fallbackBoundTemplates`) + * paired with flat O(1) top call frames (`$topCallFrame`, `$topCallThis`) that avoid nested + * stack operations on non-recursive calls. + * - Pre-compiled binding plans (`$compiledNodeBindPlanCache`, `$compiledRelativeNodeBindPlanCache`, + * `$compiledBindPlanBySigCache`, `$compiledUnionMembersCache`) and `WeakMap`-memoized + * `key-of`/`value-of` expansions (`$expandedKeyOrValueOfCache`) so repeated checks verify + * existing bindings via inline identity/name fast paths without re-running reflection or + * re-checking static upper bounds. + * - Pre-computed O(1) subtype hash matrices (`SCALAR_SUBTYPES`, `COLLECTION_SUBTYPES`, + * `INT_SUPERTYPES`, `STRING_SUPERTYPES`) and cached singleton primitive AST nodes + * (`$intNode`, `$stringNode`, `$floatNode`, `$boolNode`, `$classNodeCache`) to avoid + * per-call `TypeNode` allocations. + * - Negative and hierarchy memoization (`$noInheritedBindingsClasses`, `$realTypeSymbolCache`, + * `$subclassCache`, `$propagationPlanCache`, `$propagatedBindingsCache`) to keep repeated + * object/class lookups allocation-free. + * + * Contributor note: Preserve singleton AST node reuse and flat fast paths in `bindInstanceFromNode()`, + * `checkVariance()`, and `getInstanceBindingsFast()` to avoid regressions in generic-heavy codebases. * * @internal */ diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index fb66ce6b..73f52db1 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -43,7 +43,36 @@ use TypePHP\Internal\Wrapper\IterableWrapper; /** - * Core runtime type checking engine facade for parameter validation, return type enforcement, and variable tracking. + * Core runtime type checking engine facade for parameter validation, return type enforcement, + * property mutation checks, and generic scope tracking. + * + * Performance & Mechanical Sympathy Architecture: + * This class is the primary hot path executed on every instrumented function entry, return, + * generator yield/send, and property/collection write. Readability and strict DRY abstractions + * are intentionally traded for Zend Engine / OPcache mechanical sympathy and maximum throughput: + * + * - Inline hot paths: Common primitive, class, nullable, identity-return, and 1-level property + * dimension checks are intentionally inlined inside entry points (`setupScope()`, `checkReturn()`, + * `checkPropertyDimAssign()`, `checkPropertyMemberAssign()`) to avoid per-check PHP call-frame + * overhead (`DO_FCALL`) and temporary wrapper array allocations. + * - Local `private const` opcodes & bitmasks (`PARAM_CHECK_*`, `PROP_OP_*`, `PROP_BIT_*`): + * Opcodes are intentionally mirrored as local class constants rather than referenced across + * classes. PHP resolves local `private const` values to literal `IS_LONG` constants at compile + * time, enabling O(1) `ZEND_MATCH` jump tables and compile-time bitmask folding instead of + * O(n) runtime `FETCH_CLASS_CONSTANT` + `IS_IDENTICAL` chains. + * - Pre-compiled monomorphic execution plans: Cold reflection, PHPDoc parsing, and template + * resolution run once and compile into flat lookup caches (`$simpleScopePlanCache`, + * `$simpleReturnPlanCache`, `$simpleCtorTemplatePlanCache`, `$simpleClassStringTemplatePlanCache`, + * `$simpleGenericIterablePlanCache`, `$genericReturnPlanCache`, `$identitySelfReturnCache`, + * `$nullableReturnCache`, and trait-dispatched variants). + * - Static boolean fast-exit flags (`$isEnabled`, `$paramsEnabled`, `$returnsEnabled`, etc.): + * Synced by `Config` to allow single-opcode bailout without method calls or superglobal lookups. + * + * Contributor note: Do not extract these hot-path `match` blocks into shared helper methods or + * replace local `private const` opcodes with cross-class constants without profiling against + * CPU-bound, generic-heavy workloads. + * + * @internal */ final class RuntimeTypeChecker { From 5d0fa1ca0f5a86ca28a2d0793791541b3e8de937 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 16:58:51 +0800 Subject: [PATCH 11/15] Fix formatting in RuntimeTypeChecker docblock; remove unnecessary whitespace --- README.md | 2 +- src/Internal/RuntimeTypeChecker.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cb67c170..53f3e283 100644 --- a/README.md +++ b/README.md @@ -313,7 +313,7 @@ TypePHP stands on the shoulders of giants. It simply would not exist without the * **[Blackfire](https://www.blackfire.io/)**: A huge thank you to **Blackfire** for generously providing a **free 1-year open-source subscription** for TypePHP. Blackfire's deterministic call-graph and memory profiling made it possible to hunt down hot-path bottlenecks and achieve up to an **11× speedup** on generics-heavy workloads. * **[`php-spx`](https://github.com/NoiseByNorthwest/php-spx)**: - Many thanks to the `php-spx` PHP profiling extension—its lightweight flamegraphs, flat execution profiles, and built-in web UI were instrumental in pinpointing tight-loop overhead and tuning TypePHP's runtime engine. + Many thanks to the `php-spx` PHP profiling extension and its lightweight flamegraphs, flat execution profiles, and built-in web UI were instrumental in pinpointing tight-loop overhead and tuning TypePHP's runtime engine. --- diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 73f52db1..3cb5adc1 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -71,7 +71,7 @@ * Contributor note: Do not extract these hot-path `match` blocks into shared helper methods or * replace local `private const` opcodes with cross-class constants without profiling against * CPU-bound, generic-heavy workloads. - * + * * @internal */ final class RuntimeTypeChecker From 45d460176a2601a7b0be3d674706f2c8530c2393 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 17:38:12 +0800 Subject: [PATCH 12/15] Enhance ContractVisitor and ScopeManager for improved type handling; add property alias management and update inferred types registration --- src/Internal/Ast/ContractVisitor.php | 251 +++++++++++++-- src/Internal/Ast/ScopeManager.php | 82 ++++- .../GenericReferenceSemanticsTest.php | 293 ++++++++++++++++++ 3 files changed, 605 insertions(+), 21 deletions(-) create mode 100644 tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index bcd33434..b52e4106 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -224,7 +224,7 @@ public function enterNode(Node $node): Node|array|null if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) { $this->scopeManager->pushScope(isIsolated: true); - $this->registerParamInferredTypes($node->params); + $this->registerParamInferredTypes($node->params, $node->getDocComment()?->getText()); } elseif ($node instanceof Node\Expr\Closure) { $capturedVars = []; foreach ($node->uses as $u) { @@ -237,7 +237,7 @@ public function enterNode(Node $node): Node|array|null } } $this->scopeManager->pushScope(isIsolated: true, initialBindings: $capturedVars); - $this->registerParamInferredTypes($node->params); + $this->registerParamInferredTypes($node->params, $node->getDocComment()?->getText()); } elseif ($this->isSoftScopeBoundary($node)) { $this->scopeManager->pushScope(isIsolated: false); } elseif ($node instanceof Node\Stmt\If_) { @@ -336,7 +336,11 @@ public function enterNode(Node $node): Node|array|null return $this->handleAssign($node); } elseif ($node instanceof Node\Expr\AssignRef) { - $this->handleAssignRef($node); + if ($node->getAttribute('typephp_wrapped') === true) { + return null; + } + + return $this->handleAssignRef($node); } return null; @@ -1893,6 +1897,18 @@ private function handleAssign(Node\Expr\Assign $node): ?Node $this->scopeManager->unregisterInferredVarType($varName); } + $propAlias = $this->scopeManager->getPropertyAlias($varName); + if ($propAlias !== null) { + $node->expr = $this->wrapPropertyCheck( + $node->expr, + clone $propAlias['targetExpr'], + $propAlias['propName'], + $node->var->getStartLine() + ); + + return null; + } + $typeString = $this->scopeManager->getVarTypeFromScope($varName); if ($typeString !== null) { @@ -2035,19 +2051,100 @@ private function collectObjectGenericNodes(TypeNode $node): array return []; } - private function handleAssignRef(Node\Expr\AssignRef $node): void + private function handleAssignRef(Node\Expr\AssignRef $node): ?Node { - if (! ($node->var instanceof Node\Expr\Variable) || ! \is_string($node->var->name)) { + $line = $node->var->getStartLine(); + $cleanTarget = $node->var; + $cleanRhs = $node->expr; + + $isVarTarget = $cleanTarget instanceof Node\Expr\Variable && \is_string($cleanTarget->name); + $explicitVarType = ($isVarTarget && ! $this->scopeManager->isAliasDeducedVar($cleanTarget->name)) + ? $this->scopeManager->getVarTypeFromScope($cleanTarget->name) + : null; + + $needsPreCheck = $isVarTarget ? ($explicitVarType !== null) : true; + /** @var list $preAssignments */ + $preAssignments = []; + $wrappedCheck = null; + + if ($needsPreCheck) { + if ($this->targetHasSideEffects($cleanTarget)) { + $cleanTarget = $this->hoistImpureTarget($cleanTarget, $preAssignments); + $this->markWriteContext($cleanTarget); + } + + if ($this->targetHasSideEffects($cleanRhs)) { + if ($cleanRhs instanceof Node\Expr\CallLike) { + $tempVar = new Node\Expr\Variable('__typephpTgt' . $this->hoistTempCounter++); + $preAssignments[] = new Node\Expr\AssignRef($tempVar, $cleanRhs); + $cleanRhs = new Node\Expr\Variable($tempVar->name); + } else { + $cleanRhs = $this->hoistImpureTarget($cleanRhs, $preAssignments); + } + $this->markWriteContext($cleanRhs); + } + + if ($isVarTarget && $explicitVarType !== null) { + /** @var Node\Expr\Variable $cleanTarget */ + /** @var string $varName */ + $varName = $cleanTarget->name; + $wrappedCheck = $this->wrapVariableCheck(clone $cleanRhs, $explicitVarType, $varName, $line); + } else { + $wrappedCheck = $this->wrapTargetMutation($cleanTarget, clone $cleanRhs, $line); + } + } + + $this->updateAssignRefAliasScope($cleanTarget, $cleanRhs, $explicitVarType !== null); + + if ($wrappedCheck === null) { + return null; + } + + $assignRef = ($cleanTarget === $node->var && $cleanRhs === $node->expr) + ? $node + : new Node\Expr\AssignRef($cleanTarget, $cleanRhs); + $assignRef->setAttribute('typephp_wrapped', true); + + if ($wrappedCheck instanceof Node\Expr\Ternary) { + $wrappedCheck->else = $assignRef; + + return $this->wrapWithPreEvaluations($preAssignments, $wrappedCheck); + } + + return $this->wrapWithPreEvaluations($preAssignments, $assignRef); + } + + private function updateAssignRefAliasScope(Node\Expr $target, Node\Expr $rhs, bool $hasExplicitTargetVarType): void + { + if (! ($target instanceof Node\Expr\Variable) || ! \is_string($target->name)) { return; } - $aliasName = $node->var->name; + $aliasName = $target->name; + + if ($hasExplicitTargetVarType) { + $this->scopeManager->unregisterPropertyAlias($aliasName); + + return; + } + + if ($rhs instanceof Node\Expr\Variable && \is_string($rhs->name)) { + $rhsPropAlias = $this->scopeManager->getPropertyAlias($rhs->name); + if ($rhsPropAlias !== null) { + $this->scopeManager->unregisterVarType($aliasName); + $this->scopeManager->registerPropertyAlias($aliasName, clone $rhsPropAlias['targetExpr'], $rhsPropAlias['propName']); + + return; + } + } + $deducedType = null; + $ownerTypeForDeduction = null; - if ($node->expr instanceof Node\Expr\Variable && \is_string($node->expr->name)) { - $deducedType = $this->scopeManager->getVarTypeFromScope($node->expr->name) - ?? $this->scopeManager->getInferredVarType($node->expr->name); - } elseif (($chainInfo = $this->extractMemberChain($node->expr)) !== null) { + if ($rhs instanceof Node\Expr\Variable && \is_string($rhs->name)) { + $deducedType = $this->scopeManager->getVarTypeFromScope($rhs->name) + ?? $this->scopeManager->getInferredVarType($rhs->name); + } elseif (($chainInfo = $this->extractMemberChain($rhs)) !== null) { $root = $chainInfo['root']; $chain = $chainInfo['chain']; $currType = null; @@ -2065,17 +2162,94 @@ private function handleAssignRef(Node\Expr\AssignRef $node): void } if (\is_string($currType) && $currType !== '') { + $ownerTypeForDeduction = $currType; $deducedType = $this->deduceMemberChainType($currType, $chain); } } - if (\is_string($deducedType) && $deducedType !== '') { - $this->scopeManager->registerVarType($aliasName, $deducedType, overwrite: true); + $hasUnresolvableTemplate = $deducedType !== null + && $ownerTypeForDeduction !== null + && $this->hasUnresolvableOwnerTemplate($deducedType, $ownerTypeForDeduction, $rhs); + + if ($hasUnresolvableTemplate || $deducedType === null) { + if ( + $rhs instanceof Node\Expr\PropertyFetch + && $rhs->name instanceof Node\Identifier + && ! $this->targetHasSideEffects($rhs->var) + ) { + $rootType = null; + if ($rhs->var instanceof Node\Expr\Variable && \is_string($rhs->var->name)) { + $rootType = $this->scopeManager->getVarTypeFromScope($rhs->var->name) + ?? $this->scopeManager->getInferredVarType($rhs->var->name); + } + + if ($rootType === null || ! str_contains($rootType, '{')) { + $this->scopeManager->unregisterVarType($aliasName); + $this->scopeManager->registerPropertyAlias($aliasName, clone $rhs->var, $rhs->name->toString()); + + return; + } + } elseif ( + $rhs instanceof Node\Expr\StaticPropertyFetch + && $rhs->name instanceof Node\VarLikeIdentifier + && ! $this->targetHasSideEffects($rhs->class) + ) { + $classArg = $this->resolveStaticClassArg($rhs->class); + $this->scopeManager->unregisterVarType($aliasName); + $this->scopeManager->registerPropertyAlias($aliasName, $classArg, $rhs->name->toString()); + + return; + } + } + + $this->scopeManager->unregisterPropertyAlias($aliasName); + + if (\is_string($deducedType) && $deducedType !== '' && ! $hasUnresolvableTemplate) { + $this->scopeManager->registerVarType($aliasName, $deducedType, overwrite: true, isAlias: true); } else { $this->scopeManager->unregisterVarType($aliasName); } } + private function hasUnresolvableOwnerTemplate(string $deducedType, string $ownerType, Node\Expr $rhs): bool + { + $curr = $rhs; + while ($curr instanceof Node\Expr\ArrayDimFetch || $curr instanceof Node\Expr\PropertyFetch) { + $curr = $curr->var; + } + + if ($curr instanceof Node\Expr\Variable && $curr->name === 'this') { + return false; + } + + $baseClass = ($pos = strpos($ownerType, '<')) !== false ? trim(substr($ownerType, 0, $pos)) : trim($ownerType); + $baseClass = ltrim($baseClass, '\\'); + if ($baseClass === '') { + return false; + } + + $shortBase = ($slashPos = strrpos($baseClass, '\\')) !== false ? substr($baseClass, $slashPos + 1) : $baseClass; + $ownerTemplates = $this->localClassTemplates[$baseClass] ?? ($this->localClassTemplates[$shortBase] ?? null); + + if ( + $ownerTemplates === null + && (class_exists($baseClass, false) || interface_exists($baseClass, false) || trait_exists($baseClass, false)) + ) { + $ownerTemplates = array_keys(DocblockParser::parseClassTemplates($baseClass)); + } + + if ($ownerTemplates === null || $ownerTemplates === []) { + return false; + } + + $parsed = $this->parseUnsetTypeCached($deducedType); + if ($parsed === null) { + return false; + } + + return DocblockParser::typeReferencesTemplate($parsed, array_fill_keys($ownerTemplates, true)); + } + private function handleForeachTypePropagation(Node\Stmt\Foreach_ $node): void { $containerType = null; @@ -2238,7 +2412,7 @@ private function targetHasSideEffects(Node $node): bool } /** - * @param list $preAssignments + * @param list $preAssignments */ private function hoistImpureTarget(Node\Expr $target, array &$preAssignments): Node\Expr { @@ -2290,7 +2464,7 @@ private function hoistImpureTarget(Node\Expr $target, array &$preAssignments): N } /** - * @param list $preAssignments + * @param list $preAssignments */ private function createHoistedTemp(Node\Expr $expr, array &$preAssignments): Node\Expr\Variable { @@ -2301,7 +2475,7 @@ private function createHoistedTemp(Node\Expr $expr, array &$preAssignments): Nod } /** - * @param list $preAssignments + * @param list $preAssignments */ private function wrapWithPreEvaluations(array $preAssignments, Node\Expr $expr): Node\Expr { @@ -2332,6 +2506,17 @@ private function wrapTargetMutation(Node\Expr $target, Node\Expr $valueExpr, int { if ($target instanceof Node\Expr\Variable && \is_string($target->name)) { $varName = $target->name; + + $propAlias = $this->scopeManager->getPropertyAlias($varName); + if ($propAlias !== null) { + return $this->wrapPropertyCheck( + $valueExpr, + clone $propAlias['targetExpr'], + $propAlias['propName'], + $line + ); + } + $typeString = $this->scopeManager->getVarTypeFromScope($varName); if ($typeString !== null) { @@ -2343,6 +2528,18 @@ private function wrapTargetMutation(Node\Expr $target, Node\Expr $valueExpr, int if ($root instanceof Node\Expr\Variable && \is_string($root->name)) { $varName = $root->name; + + $propAlias = $this->scopeManager->getPropertyAlias($varName); + if ($propAlias !== null) { + return $this->wrapPropertyMemberAssignCheck( + $valueExpr, + clone $propAlias['targetExpr'], + $propAlias['propName'], + $chain, + $line + ); + } + $typeString = $this->scopeManager->getVarTypeFromScope($varName); if ($typeString !== null && $this->shouldHandleMemberAssignCheck($typeString, $chain)) { @@ -2468,13 +2665,29 @@ private function resolveClassNameFromNode(Node\Name $classNode): ?string * * @param array $params */ - private function registerParamInferredTypes(array $params): void + private function registerParamInferredTypes(array $params, ?string $docText = null): void { + $docParamTypes = []; + if ($docText !== null && str_contains($docText, '@param')) { + try { + $phpDocNode = DocblockExtractor::parseDocString($docText); + foreach (DocblockExtractor::getParamTags($phpDocNode) as $pName => $pTag) { + $docParamTypes[$pName] = (string) $pTag->type; + } + } catch (\Throwable) { + } + } + foreach ($params as $param) { if ($param->var instanceof Node\Expr\Variable && \is_string($param->var->name) && $param->type instanceof Node\Name) { - $pClass = $this->resolveClassNameFromNode($param->type); - if ($pClass !== null) { - $this->scopeManager->registerInferredVarType($param->var->name, $pClass); + $pName = $param->var->name; + if (isset($docParamTypes[$pName])) { + $this->scopeManager->registerInferredVarType($pName, $docParamTypes[$pName]); + } else { + $pClass = $this->resolveClassNameFromNode($param->type); + if ($pClass !== null) { + $this->scopeManager->registerInferredVarType($pName, $pClass); + } } } } diff --git a/src/Internal/Ast/ScopeManager.php b/src/Internal/Ast/ScopeManager.php index 170dda7a..c0b11b14 100644 --- a/src/Internal/Ast/ScopeManager.php +++ b/src/Internal/Ast/ScopeManager.php @@ -27,6 +27,21 @@ final class ScopeManager */ private array $inferredStack = [[]]; + /** + * In-memory stack of property reference aliases ($ref = &$obj->prop or $ref = &Cls::$prop). + * + * @var list> + */ + private array $propertyAliasStack = [[]]; + + /** + * Tracks variable names whose scopeStack entry came from AssignRef alias deduction + * (as opposed to an explicit @var annotation). + * + * @var list> + */ + private array $aliasDeducedStack = [[]]; + /** * Tracks which scope frames are isolated boundaries (functions, methods, closures). * @@ -46,19 +61,72 @@ public function unregisterVarType(string $varName): void { unset($this->scopeStack[$this->depth][$varName]); unset($this->inferredStack[$this->depth][$varName]); + unset($this->propertyAliasStack[$this->depth][$varName]); + unset($this->aliasDeducedStack[$this->depth][$varName]); + } + + public function registerPropertyAlias(string $varName, Node\Expr $targetExpr, string $propName): void + { + $this->propertyAliasStack[$this->depth][$varName] = [ + 'targetExpr' => $targetExpr, + 'propName' => $propName, + ]; + } + + public function unregisterPropertyAlias(string $varName): void + { + unset($this->propertyAliasStack[$this->depth][$varName]); + } + + /** + * @return array{targetExpr: Node\Expr, propName: string}|null + */ + public function getPropertyAlias(string $varName): ?array + { + for ($i = $this->depth; $i >= 0; $i--) { + if (isset($this->propertyAliasStack[$i][$varName])) { + return $this->propertyAliasStack[$i][$varName]; + } + + if ($this->isolatedStack[$i]) { + break; + } + } + + return null; } /** * Programmatically registers a variable's type into the current scope frame. * Preserves explicit inline @var declarations in the current frame unless overwrite is true. */ - public function registerVarType(string $varName, string $typeString, bool $overwrite = false): void + public function registerVarType(string $varName, string $typeString, bool $overwrite = false, bool $isAlias = false): void { if (! $overwrite && isset($this->scopeStack[$this->depth][$varName])) { return; } $this->scopeStack[$this->depth][$varName] = $typeString; + if ($isAlias) { + $this->aliasDeducedStack[$this->depth][$varName] = true; + } else { + unset($this->aliasDeducedStack[$this->depth][$varName]); + } + } + + public function isAliasDeducedVar(string $varName): bool + { + for ($i = $this->depth; $i >= 0; $i--) { + if (isset($this->scopeStack[$i][$varName])) { + return isset($this->aliasDeducedStack[$i][$varName]); + } + + if ($this->isolatedStack[$i]) { + break; + } + } + + return false; } /** @@ -88,6 +156,8 @@ public function pushScope(bool $isIsolated = false, array $initialBindings = []) $this->depth++; $this->scopeStack[] = $initialBindings; $this->inferredStack[] = []; + $this->propertyAliasStack[] = []; + $this->aliasDeducedStack[] = []; $this->isolatedStack[] = $isIsolated; } @@ -99,6 +169,8 @@ public function popScope(): void if ($this->depth > 0) { array_pop($this->scopeStack); array_pop($this->inferredStack); + array_pop($this->propertyAliasStack); + array_pop($this->aliasDeducedStack); array_pop($this->isolatedStack); $this->depth--; } @@ -122,7 +194,12 @@ public function extractVarDocblock(string $docText, ?Node\Expr $expr = null): vo $typeString = (string) $varTag->type; $varName = ltrim($varTag->variableName, '$'); - if ($varName === '' && $expr instanceof Node\Expr\Assign && $expr->var instanceof Node\Expr\Variable && \is_string($expr->var->name)) { + if ( + $varName === '' + && ($expr instanceof Node\Expr\Assign || $expr instanceof Node\Expr\AssignRef) + && $expr->var instanceof Node\Expr\Variable + && \is_string($expr->var->name) + ) { $varName = $expr->var->name; } elseif ($varName === '' && $expr instanceof Node\Expr\Variable && \is_string($expr->name)) { $varName = $expr->name; @@ -130,6 +207,7 @@ public function extractVarDocblock(string $docText, ?Node\Expr $expr = null): vo if ($varName !== '') { $this->scopeStack[$this->depth][$varName] = $typeString; + unset($this->aliasDeducedStack[$this->depth][$varName]); } } } catch (\Throwable $e) { diff --git a/tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php b/tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php new file mode 100644 index 00000000..483d3f34 --- /dev/null +++ b/tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php @@ -0,0 +1,293 @@ +item = $item; + } +} + +final class RefTypedHolder +{ + /** + * @var positive-int + */ + public int $score = 10; + + /** + * @var list + */ + public array $numbers = [1, 2, 3]; + + /** + * @var positive-int + */ + public static int $limit = 100; +} + +final class RefBoxFactory +{ + public int $calls = 0; + + /** + * @var RefBox + */ + public RefBox $box; + + public function __construct() + { + /** @var RefBox $b */ + $b = new RefBox(new RefUser('FactoryUser')); + $this->box = $b; + } + + /** + * @return RefBox + */ + public function next(): RefBox + { + $this->calls++; + + return $this->box; + } +} + +/** + * @param RefBox $box + */ +function refCorruptWithParamDoc(RefBox $box): void +{ + $ref = &$box->item; + $ref = new RefProduct('SKU-999'); +} + +/** + * @param RefBox $box + */ +function refUpdateValidWithParamDoc(RefBox $box): void +{ + $ref = &$box->item; + $ref = new RefUser('Alice Updated'); +} + +function refCorruptWithoutParamDoc(RefBox $box): void +{ + $ref = &$box->item; + $ref = new RefProduct('SKU-888'); +} + +function refUpdateValidWithoutParamDoc(RefBox $box): void +{ + $ref = &$box->item; + $ref = new RefUser('Bob Updated'); +} + +describe('Generic & Typed Reference Semantics (Red Phase)', function () { + describe('1. Local Reference Alias to Generic Object Property ($ref = &$box->item)', function () { + test('rejects invalid mutation through $ref with concrete bound type (RefUser, not raw T) when @param doc is present', function () { + /** @var RefBox $userBox */ + $userBox = new RefBox(new RefUser('Alice')); + + expect(fn () => refCorruptWithParamDoc($userBox)) + ->toThrow(TypeError::class, RefUser::class) + ; + + expect($userBox->item)->toBeInstanceOf(RefUser::class) + ->and($userBox->item->name)->toBe('Alice') + ; + }); + + test('allows valid RefUser mutation through $ref inside function with @param Box', function () { + /** @var RefBox $userBox */ + $userBox = new RefBox(new RefUser('Alice')); + + refUpdateValidWithParamDoc($userBox); + + expect($userBox->item)->toBeInstanceOf(RefUser::class) + ->and($userBox->item->name)->toBe('Alice Updated') + ; + }); + + test('enforces live WeakMap generic binding through $ref even without @param Box docblock', function () { + /** @var RefBox $userBox */ + $userBox = new RefBox(new RefUser('Bob')); + + expect(fn () => refCorruptWithoutParamDoc($userBox)) + ->toThrow(TypeError::class, RefUser::class) + ; + + refUpdateValidWithoutParamDoc($userBox); + + expect($userBox->item)->toBeInstanceOf(RefUser::class) + ->and($userBox->item->name)->toBe('Bob Updated') + ; + }); + + test('releases property alias on unset($ref) and updates target on rebinding $ref = &$otherBox->item', function () { + /** @var RefBox $userBox */ + $userBox = new RefBox(new RefUser('Charlie')); + + /** @var RefBox $productBox */ + $productBox = new RefBox(new RefProduct('SKU-1')); + + $ref = &$userBox->item; + $ref = new RefUser('Charlie Updated'); + expect($userBox->item->name)->toBe('Charlie Updated'); + + // Rebind $ref to $productBox->item + $ref = &$productBox->item; + $ref = new RefProduct('SKU-2'); + expect($productBox->item->sku)->toBe('SKU-2') + ->and($userBox->item->name)->toBe('Charlie Updated') + ; + + // Break reference with unset($ref): reassigning $ref should no longer enforce $productBox->item + unset($ref); + $ref = new RefUser('Detached'); + expect($ref)->toBeInstanceOf(RefUser::class) + ->and($productBox->item->sku)->toBe('SKU-2') + ; + }); + }); + + describe('2. Assign-by-Reference Across Properties ($a->item = &$b->item)', function () { + test('rejects binding Box::$item by reference to Box::$item and preserves original value', function () { + /** @var RefBox $userBox */ + $userBox = new RefBox(new RefUser('Bob')); + + /** @var RefBox $productBox */ + $productBox = new RefBox(new RefProduct('SKU-1')); + + expect(function () use ($userBox, $productBox): void { + $userBox->item = &$productBox->item; + })->toThrow(TypeError::class, RefUser::class); + + expect($userBox->item)->toBeInstanceOf(RefUser::class) + ->and($userBox->item->name)->toBe('Bob') + ; + }); + + test('allows binding compatible Box::$item by reference and preserves reference semantics', function () { + /** @var RefBox $boxA */ + $boxA = new RefBox(new RefUser('Alice')); + + /** @var RefBox $boxB */ + $boxB = new RefBox(new RefUser('Bob')); + + $boxA->item = &$boxB->item; + expect($boxA->item->name)->toBe('Bob'); + + $boxB->item = new RefUser('Shared'); + expect($boxA->item->name)->toBe('Shared'); + }); + + test('rejects assign-by-reference violating non-generic instance and static property contracts', function () { + $holder = new RefTypedHolder(); + $invalid = -5; + + expect(function () use ($holder, &$invalid): void { + $holder->score = &$invalid; + })->toThrow(TypeError::class, 'positive-int'); + expect($holder->score)->toBe(10); + + RefTypedHolder::$limit = 100; + $invalidStatic = -10; + + expect(function () use (&$invalidStatic): void { + RefTypedHolder::$limit = &$invalidStatic; + })->toThrow(TypeError::class, 'positive-int'); + expect(RefTypedHolder::$limit)->toBe(100); + }); + }); + + describe('3. Assign-by-Reference to Typed Variables, Array Shapes & Property Dimensions', function () { + test('validates assign-by-reference against existing typed local variable contract', function () { + /** @var positive-int $count */ + $count = 10; + $bad = -5; + + expect(function () use (&$count, &$bad): void { + /** @var positive-int $count */ + $count = &$bad; + })->toThrow(TypeError::class, 'positive-int'); + expect($count)->toBe(10); + + $good = 25; + $count = &$good; + expect($count)->toBe(25); + + $good = 30; + expect($count)->toBe(30); + }); + + test('validates assign-by-reference on typed array shape dimension', function () { + /** @var array{count: positive-int} $stats */ + $stats = ['count' => 1]; + $bad = -5; + + expect(function () use (&$stats, &$bad): void { + /** @var array{count: positive-int} $stats */ + $stats['count'] = &$bad; + })->toThrow(TypeError::class, 'positive-int'); + expect($stats['count'])->toBe(1); + }); + + test('validates assign-by-reference on typed object array property dimension', function () { + $holder = new RefTypedHolder(); + $bad = -99; + + expect(function () use ($holder, &$bad): void { + $holder->numbers[0] = &$bad; + })->toThrow(TypeError::class, 'positive-int'); + expect($holder->numbers[0])->toBe(1); + }); + }); + + describe('4. Impure Target Single-Evaluation on AssignRef', function () { + test('evaluates impure property receiver only once during assign-by-reference', function () { + $factory = new RefBoxFactory(); + $source = new RefBox(new RefUser('Updated')); + + $factory->next()->item = &$source->item; + + expect($factory->calls)->toBe(1) + ->and($factory->box->item->name)->toBe('Updated') + ; + + $source->item = new RefUser('SharedAfter'); + expect($factory->box->item->name)->toBe('SharedAfter'); + }); + }); +}); From 68014bb9c5195d7154c64ae55fb6ade1fe4623f8 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 17:42:34 +0800 Subject: [PATCH 13/15] Refactor test descriptions to remove "Red Phase" terminology for clarity --- .../Ast/ContractVisitorWriteContextAndDuplicationTest.php | 2 +- .../Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php | 2 +- tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php | 2 +- tests/Internal/Ast/ReturnVarDoubleWrappingTest.php | 2 +- .../Internal/Docblock/DocblockNormalizerNestedGenericsTest.php | 2 +- tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php | 2 +- tests/Internal/Io/StreamWrapperExceptionSafetyTest.php | 2 +- tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php | 2 +- .../ArraysAndShapes/CrossNamespaceImportedTypeAliasTest.php | 2 +- .../TypeChecking/ArraysAndShapes/MemberUnsetValidationTest.php | 2 +- tests/TypeChecking/Boundaries/Priority1BugsTest.php | 2 +- tests/TypeChecking/Boundaries/Priority2BugsTest.php | 2 +- tests/TypeChecking/Boundaries/Priority3BugsTest.php | 2 +- tests/TypeChecking/Boundaries/Priority4BugsTest.php | 2 +- .../Conditionals/ConditionalWithClassConstantTest.php | 2 +- tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php | 2 +- .../Generics/NullableAndUnionGenericPrebindingTest.php | 2 +- tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php | 2 +- tests/Unit/UnannotatedNativeReturnInjectionTest.php | 2 +- 19 files changed, 19 insertions(+), 19 deletions(-) diff --git a/tests/Internal/Ast/ContractVisitorWriteContextAndDuplicationTest.php b/tests/Internal/Ast/ContractVisitorWriteContextAndDuplicationTest.php index ce9b05d0..6abb9350 100644 --- a/tests/Internal/Ast/ContractVisitorWriteContextAndDuplicationTest.php +++ b/tests/Internal/Ast/ContractVisitorWriteContextAndDuplicationTest.php @@ -7,7 +7,7 @@ use TypePHP\Exception\TypeError; use TypePHP\Internal\Io\StreamWrapper; -describe('ContractVisitor Write-Context & Target Duplication (Red Phase)', function () { +describe('ContractVisitor Write-Context & Target Duplication', function () { describe('1. Foreach & By-Ref ArrayItem Write Context with StaticPropertyFetch', function () { test('does not wrap foreach valueVar, keyVar, destructured target, or array-dim static property in checkStaticProperty', function () { $source = <<<'PHP' diff --git a/tests/Internal/Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php b/tests/Internal/Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php index 0fccfdcf..516aecc1 100644 --- a/tests/Internal/Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php +++ b/tests/Internal/Ast/Elimination/ArrayLiteralSpreadSoundnessTest.php @@ -20,7 +20,7 @@ use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Io\StreamWrapper; -describe('ArrayLiteralEvaluator Spread (...$x) Soundness (Red Phase)', function () { +describe('ArrayLiteralEvaluator Spread (...$x) Soundness', function () { describe('1. Bare Identifiers (list, non-empty-array, non-empty-list)', function () { test('does not eliminate spread expressions against list, non-empty-array, or non-empty-list', function () { $spreadExpr = new Array_([ diff --git a/tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php b/tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php index 969e22cf..e8a2aa99 100644 --- a/tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php +++ b/tests/Internal/Ast/Elimination/ConstantAndEnumSoundnessTest.php @@ -47,7 +47,7 @@ enum SoundnessEnumWithConst: string case Active = 'active'; } -describe('ConstantAndEnumEvaluator Soundness (Red Phase)', function () { +describe('ConstantAndEnumEvaluator Soundness', function () { describe('1. Cross-Class Constant & Wildcard Isolation', function () { test('does not eliminate ClassConstFetch when expression class differs from ConstTypeNode class', function () { $fetch = new ClassConstFetch(new Name('User'), new Identifier('STATUS_PAID')); diff --git a/tests/Internal/Ast/ReturnVarDoubleWrappingTest.php b/tests/Internal/Ast/ReturnVarDoubleWrappingTest.php index d78e6bc0..62ac8c89 100644 --- a/tests/Internal/Ast/ReturnVarDoubleWrappingTest.php +++ b/tests/Internal/Ast/ReturnVarDoubleWrappingTest.php @@ -8,7 +8,7 @@ use TypePHP\Internal\Io\StreamWrapper; use TypePHP\Internal\Util\Config; -describe('Inline @var on return vs FunctionContractInjector (Red Phase)', function () { +describe('Inline @var on return vs FunctionContractInjector', function () { beforeEach(function () { Config::reset(); StreamWrapper::reset(); diff --git a/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php b/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php index e6138d57..ed3eea32 100644 --- a/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php +++ b/tests/Internal/Docblock/DocblockNormalizerNestedGenericsTest.php @@ -7,7 +7,7 @@ use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; -describe('DocblockNormalizer Nested Angle Brackets and Callables (Issue 5 Red Phase)', function () { +describe('DocblockNormalizer Nested Angle Brackets and Callables (Issue 5)', function () { describe('1. Callable Generic Parameter Preservation ()', function () { test('preserves generic template when auto-completing omitted return type to : mixed', function () { $doc = '/** @param callable(T) $fn */'; diff --git a/tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php b/tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php index e53d28f6..d19a2f89 100644 --- a/tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php +++ b/tests/Internal/Io/MultiNamespaceAndEnumTraitMetadataTest.php @@ -12,7 +12,7 @@ use TypePHP\Tests\Fixtures\Domain\Cat; use TypePHP\Tests\Fixtures\Domain\Dog; -describe('Multi-Namespace, Enum, and Trait Metadata Seeding (Red Phase)', function () { +describe('Multi-Namespace, Enum, and Trait Metadata Seeding', function () { beforeEach(function () { Config::reset(); StreamWrapper::reset(); diff --git a/tests/Internal/Io/StreamWrapperExceptionSafetyTest.php b/tests/Internal/Io/StreamWrapperExceptionSafetyTest.php index 81748d1f..aa324333 100644 --- a/tests/Internal/Io/StreamWrapperExceptionSafetyTest.php +++ b/tests/Internal/Io/StreamWrapperExceptionSafetyTest.php @@ -9,7 +9,7 @@ use TypePHP\Internal\Io\StreamWrapper; use TypePHP\Internal\Util\Config; -describe('StreamWrapper Exception Safety (Red Phase)', function () { +describe('StreamWrapper Exception Safety', function () { beforeEach(function () { Config::reset(); StreamWrapper::reset(); diff --git a/tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php b/tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php index 93877e4a..fe7c7774 100644 --- a/tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php +++ b/tests/Internal/Resolver/SpecialTypeResolverUseImportsTest.php @@ -11,7 +11,7 @@ class UseImportCollisionTarget { } -describe('SpecialTypeResolver & StreamWrapper Non-Class Use Import Isolation (Red Phase)', function () { +describe('SpecialTypeResolver & StreamWrapper Non-Class Use Import Isolation', function () { beforeEach(function () { SpecialTypeResolver::reset(); StreamWrapper::reset(); diff --git a/tests/TypeChecking/ArraysAndShapes/CrossNamespaceImportedTypeAliasTest.php b/tests/TypeChecking/ArraysAndShapes/CrossNamespaceImportedTypeAliasTest.php index b2e77496..3bc39585 100644 --- a/tests/TypeChecking/ArraysAndShapes/CrossNamespaceImportedTypeAliasTest.php +++ b/tests/TypeChecking/ArraysAndShapes/CrossNamespaceImportedTypeAliasTest.php @@ -60,7 +60,7 @@ }); }); - describe('2. Related Edge Cases (Expected Red Phase on v0.14.1)', function () { + describe('2. Related Edge Cases', function () { test('resolves parent alias imports when referenced by a child class @phpstan-type in another namespace', function () { $child = new PaintChildTypes(); diff --git a/tests/TypeChecking/ArraysAndShapes/MemberUnsetValidationTest.php b/tests/TypeChecking/ArraysAndShapes/MemberUnsetValidationTest.php index 9859fd25..511f9422 100644 --- a/tests/TypeChecking/ArraysAndShapes/MemberUnsetValidationTest.php +++ b/tests/TypeChecking/ArraysAndShapes/MemberUnsetValidationTest.php @@ -80,7 +80,7 @@ public function next(): MemberUnsetPropertyBox } } -describe('Member Unset Validation (Red Phase)', function () { +describe('Member Unset Validation', function () { beforeEach(function () { MemberUnsetStaticBox::reset(); Config::reset(); diff --git a/tests/TypeChecking/Boundaries/Priority1BugsTest.php b/tests/TypeChecking/Boundaries/Priority1BugsTest.php index 4242d806..2f9afbd5 100644 --- a/tests/TypeChecking/Boundaries/Priority1BugsTest.php +++ b/tests/TypeChecking/Boundaries/Priority1BugsTest.php @@ -71,7 +71,7 @@ public static function getArrowRef(): \Closure } } -describe('Priority 1 Bugs: Type Safety & Call Boundary Soundness (Red Phase)', function () { +describe('Priority 1 Bugs: Type Safety & Call Boundary Soundness', function () { beforeEach(function () { Config::reset(); TypePHP::clearViolations(); diff --git a/tests/TypeChecking/Boundaries/Priority2BugsTest.php b/tests/TypeChecking/Boundaries/Priority2BugsTest.php index 1810536b..a0be3e6d 100644 --- a/tests/TypeChecking/Boundaries/Priority2BugsTest.php +++ b/tests/TypeChecking/Boundaries/Priority2BugsTest.php @@ -56,7 +56,7 @@ public function __construct(mixed $value) } } -describe('Priority 2 Bugs: Cache Isolation, AST Printer & Class Constants (Red Phase)', function () { +describe('Priority 2 Bugs: Cache Isolation, AST Printer & Class Constants', function () { beforeEach(function () { Config::reset(); }); diff --git a/tests/TypeChecking/Boundaries/Priority3BugsTest.php b/tests/TypeChecking/Boundaries/Priority3BugsTest.php index 04750b2b..92652106 100644 --- a/tests/TypeChecking/Boundaries/Priority3BugsTest.php +++ b/tests/TypeChecking/Boundaries/Priority3BugsTest.php @@ -43,7 +43,7 @@ public function getNullableString(mixed $val): mixed } } -describe('Priority 3 Bugs: Cross-Namespace Static Elimination, Aliased Callables & Opcode Fast-Paths (Red Phase)', function () { +describe('Priority 3 Bugs: Cross-Namespace Static Elimination, Aliased Callables & Opcode Fast-Paths', function () { beforeEach(function () { Config::reset(); }); diff --git a/tests/TypeChecking/Boundaries/Priority4BugsTest.php b/tests/TypeChecking/Boundaries/Priority4BugsTest.php index ac90a071..ac77255d 100644 --- a/tests/TypeChecking/Boundaries/Priority4BugsTest.php +++ b/tests/TypeChecking/Boundaries/Priority4BugsTest.php @@ -8,7 +8,7 @@ use TypePHP\Internal\Io\StreamWrapper; use TypePHP\Internal\Util\Config; -describe('Priority 4 Bugs: Sibling Scope Isolation & Docblock Prose Heuristics (Red Phase)', function () { +describe('Priority 4 Bugs: Sibling Scope Isolation & Docblock Prose Heuristics', function () { beforeEach(function () { Config::reset(); }); diff --git a/tests/TypeChecking/Conditionals/ConditionalWithClassConstantTest.php b/tests/TypeChecking/Conditionals/ConditionalWithClassConstantTest.php index d0faf669..d345d7ca 100644 --- a/tests/TypeChecking/Conditionals/ConditionalWithClassConstantTest.php +++ b/tests/TypeChecking/Conditionals/ConditionalWithClassConstantTest.php @@ -66,7 +66,7 @@ function resolveShapeWithKeyAndConditionalConst(bool $isAdmin, mixed $roleVal, s ]; } -describe('DocblockNormalizer Class Constants in Conditional Types (Red Phase)', function () { +describe('DocblockNormalizer Class Constants in Conditional Types', function () { describe('1. DocblockNormalizer Unit Assertions', function () { test('does not quote class constant in conditional true branch', function () { $doc = '/** @return ($isAdmin is true ? Role::ADMIN : Role::USER) */'; diff --git a/tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php b/tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php index 483d3f34..4c7b5479 100644 --- a/tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php +++ b/tests/TypeChecking/Generics/GenericReferenceSemanticsTest.php @@ -114,7 +114,7 @@ function refUpdateValidWithoutParamDoc(RefBox $box): void $ref = new RefUser('Bob Updated'); } -describe('Generic & Typed Reference Semantics (Red Phase)', function () { +describe('Generic & Typed Reference Semantics', function () { describe('1. Local Reference Alias to Generic Object Property ($ref = &$box->item)', function () { test('rejects invalid mutation through $ref with concrete bound type (RefUser, not raw T) when @param doc is present', function () { /** @var RefBox $userBox */ diff --git a/tests/TypeChecking/Generics/NullableAndUnionGenericPrebindingTest.php b/tests/TypeChecking/Generics/NullableAndUnionGenericPrebindingTest.php index e31165ab..ecddeab1 100644 --- a/tests/TypeChecking/Generics/NullableAndUnionGenericPrebindingTest.php +++ b/tests/TypeChecking/Generics/NullableAndUnionGenericPrebindingTest.php @@ -59,7 +59,7 @@ public function getContent(): array } } -describe('Nullable & Union Generic Constructor Pre-binding (Red Phase)', function () { +describe('Nullable & Union Generic Constructor Pre-binding', function () { describe('0. Control: Direct GenericTypeNode Pre-binding', function () { test('prebinds T inside constructor and validates elements on entry', function () { /** @var PrebindNullableBox $box */ diff --git a/tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php b/tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php index ac468947..20dde6af 100644 --- a/tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php +++ b/tests/TypeChecking/Generics/ReentrantCallStackWideningTest.php @@ -93,7 +93,7 @@ public static function intermediateDispatch(string $tag, callable $callback): vo } } -describe('Re-entrant Call Stack Order in TemplateManager (Issue 4 Red Phase)', function () { +describe('Re-entrant Call Stack Order in TemplateManager (Issue 4)', function () { beforeEach(function () { Config::reset(); TemplateManager::reset(); diff --git a/tests/Unit/UnannotatedNativeReturnInjectionTest.php b/tests/Unit/UnannotatedNativeReturnInjectionTest.php index 603471d4..3fbce480 100644 --- a/tests/Unit/UnannotatedNativeReturnInjectionTest.php +++ b/tests/Unit/UnannotatedNativeReturnInjectionTest.php @@ -7,7 +7,7 @@ use TypePHP\Internal\Io\StreamWrapper; use TypePHP\Internal\Util\Config; -describe('Unannotated Native Return Type Injection on Non-Final Standalone Classes (Red Phase)', function () { +describe('Unannotated Native Return Type Injection on Non-Final Standalone Classes', function () { beforeEach(function () { Config::reset(); }); From 4e216ed730f6b3c470fd2f2d7d1e40488356b738 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 19:23:50 +0800 Subject: [PATCH 14/15] Fix 8.1 compatibility on failing ci --- src/Internal/Generics/TemplateManager.php | 38 ++++++++++++++++------- 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index b3bcc83b..409fcc3d 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -3369,19 +3369,33 @@ private static function extractLiteralConstValue(ConstTypeNode $node, bool &$ok) $expr = $node->constExpr; $ok = true; - return match (true) { - $expr instanceof ConstExprStringNode => $expr->value, - $expr instanceof ConstExprIntegerNode => (int) $expr->value, - $expr instanceof ConstExprFloatNode => (float) $expr->value, - $expr instanceof ConstExprTrueNode => true, - $expr instanceof ConstExprFalseNode => false, - $expr instanceof ConstExprNullNode => null, - default => (static function () use (&$ok): null { - $ok = false; + if ($expr instanceof ConstExprStringNode) { + return $expr->value; + } - return null; - })(), - }; + if ($expr instanceof ConstExprIntegerNode) { + return (int) $expr->value; + } + + if ($expr instanceof ConstExprFloatNode) { + return (float) $expr->value; + } + + if ($expr instanceof ConstExprTrueNode) { + return true; + } + + if ($expr instanceof ConstExprFalseNode) { + return false; + } + + if ($expr instanceof ConstExprNullNode) { + return null; + } + + $ok = false; + + return null; } /** From f6605ee4d4f1b83d2d753dba5d4bb89128bd953a Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 25 Nov 2026 19:30:59 +0800 Subject: [PATCH 15/15] Fix formatting in DocblockNormalizerTest to improve readability --- tests/Internal/Docblock/DocblockNormalizerTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Internal/Docblock/DocblockNormalizerTest.php b/tests/Internal/Docblock/DocblockNormalizerTest.php index b19e1b72..fb79c8f7 100644 --- a/tests/Internal/Docblock/DocblockNormalizerTest.php +++ b/tests/Internal/Docblock/DocblockNormalizerTest.php @@ -709,7 +709,8 @@ expect(fn () => $inner('hello'))->toThrow(TypeError::class); expect(TypeDeducer::deduceDimType('array{string, ...float[]}', new LNumber(3))) - ->toBe('float'); + ->toBe('float') + ; }); }); });