From 248b811b4dd1490802555f182f5df2c4de1c8296 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 17 Nov 2026 11:44:21 +0800 Subject: [PATCH 01/25] Introduce targeted optimization for bottlenecks found via profiler --- src/Internal/Checker/ParamChecker.php | 103 +++++++++++-- src/Internal/Checker/ReturnChecker.php | 46 +++--- src/Internal/Docblock/DocblockParser.php | 54 ++++++- .../Resolver/CallerBoundaryResolver.php | 15 +- src/Internal/RuntimeTypeChecker.php | 126 +++++++++++++--- src/Internal/Util/Config.php | 59 +++++++- .../Validator/ArrayShapeValidator.php | 103 +++++++++---- .../Validator/CollectionElementValidator.php | 40 ++++- src/Internal/Validator/GenericValidator.php | 25 ++-- .../Validator/TypeValidatorRegistry.php | 18 +++ src/Internal/Validator/UnionValidator.php | 140 ++++++++++++++++++ tests/Internal/Util/ConfigTest.php | 6 +- 12 files changed, 608 insertions(+), 127 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index d28acd5f..49128d2e 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -69,6 +69,21 @@ final class ParamChecker 'non-empty-list' => true, ]; + public const KIND_NORMAL = 0; + + public const KIND_CONSTRUCT = 1; + + public const KIND_MAGIC_CALL = 2; + + public const KIND_MAGIC_GET = 4; + + /** + * In-memory cache for method kind flags: [$effectiveFunction] => int (KIND_*). + * + * @var array + */ + public static array $functionKindCache = []; + /** * 2D Cache for effective functions: [$function][$actualClassName] => effectiveFunction. * @@ -141,6 +156,7 @@ public static function reset(): void { self::$effectiveFunctionCache = []; self::$noParamContractCache = []; + self::$functionKindCache = []; self::$classDeclaredTemplateNamesCache = []; ClassNameValidator::reset(); self::$baseTypeCache = []; @@ -157,7 +173,7 @@ public static function reset(): void */ public static function areAllParamsUnconstrained(string $effectiveFunction): bool { - if (str_contains($effectiveFunction, '__call') || str_ends_with($effectiveFunction, '::__get')) { + if ((self::$functionKindCache[$effectiveFunction] ??= self::detectFunctionKind($effectiveFunction)) >= self::KIND_MAGIC_CALL) { return false; } @@ -201,8 +217,9 @@ public static function checkParams( $effectiveFunction = self::resolveEffectiveFunction($function, $thisOrClass, $thisObj); } - $isMagicCall = str_ends_with($effectiveFunction, '::__call') || str_ends_with($effectiveFunction, '::__callStatic'); - $isMagicGet = str_ends_with($effectiveFunction, '::__get'); + $functionKind = self::$functionKindCache[$effectiveFunction] ??= self::detectFunctionKind($effectiveFunction); + $isMagicCall = ($functionKind === self::KIND_MAGIC_CALL); + $isMagicGet = ($functionKind === self::KIND_MAGIC_GET); if (! $isMagicCall && ! $isMagicGet && isset(self::$noParamContractCache[$effectiveFunction])) { return null; @@ -212,11 +229,11 @@ public static function checkParams( return null; } - $magicError = self::handleMagicCall($effectiveFunction, $vars, $thisObj, $registry); - if ($magicError !== null) { - return $magicError; + if ($isMagicCall) { + return self::handleMagicCall($effectiveFunction, $vars, $thisObj, $registry); } - if ($isMagicCall || $isMagicGet) { + + if ($isMagicGet) { return null; } @@ -237,7 +254,15 @@ public static function checkParams( $sensitiveParams = $contract['sensitiveParams'] ?? []; if (! $paramsUseGenerics && ! $hasMethodTemplates && \count($aliases) === 0 && ! $paramsAreDynamic) { - return self::validateSimpleParams($contract['types'], $vars, $effectiveFunction, $registry, $sensitiveParams); + return self::validateSimpleParams( + $contract['constrainedTypes'] ?? $contract['types'], + $vars, + $effectiveFunction, + $registry, + $sensitiveParams, + $contract['paramConditionals'] ?? null, + ! isset($contract['constrainedTypes']) + ); } self::prepareGenericBindings($effectiveFunction, $methodTemplates, $thisObj, $classTemplates, $thisOrClass); @@ -308,22 +333,33 @@ private static function refineInferredTypeFromBound(mixed $val, TypeNode $bound, * @param array $types * @param array $vars * @param array $sensitiveParams + * @param array|null $paramConditionals */ - private static function validateSimpleParams( + public static function validateSimpleParams( array $types, array $vars, string $effectiveFunction, TypeValidatorRegistry $registry, - array $sensitiveParams = [] + array $sensitiveParams = [], + ?array $paramConditionals = null, + bool $filterUnconstrained = false ): ?ErrorMessage { foreach ($types as $paramName => $typeNode) { if (isset($vars[$paramName]) || \array_key_exists($paramName, $vars)) { - if (! ($typeNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($typeNode)) { + if ($paramConditionals === null) { + if (! ($typeNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, $vars, [], $registry, $effectiveFunction); + if (self::isUnconstrained($typeNode)) { + continue; + } + } elseif ($filterUnconstrained && self::isUnconstrained($typeNode)) { + continue; + } + } elseif (isset($paramConditionals[$paramName])) { $typeNode = ConditionalChecker::resolve($typeNode, $vars, [], $registry, $effectiveFunction); - } - - if (self::isUnconstrained($typeNode)) { - continue; + if (self::isUnconstrained($typeNode)) { + continue; + } } $isSensitive = $sensitiveParams[$paramName] ?? false; @@ -501,10 +537,24 @@ private static function validateAllParameters( */ public static function resolveEffectiveFunction(string $function, object|string|null $thisOrClass, ?object $thisObj = null): string { - if (! str_contains($function, '::')) { + if ($thisOrClass === null) { return $function; } + $actualClassName = \is_object($thisOrClass) ? $thisOrClass::class : $thisOrClass; + + if ($actualClassName === '') { + return $function; + } + + if (isset(self::$effectiveFunctionCache[$function][$actualClassName])) { + return self::$effectiveFunctionCache[$function][$actualClassName]; + } + + if (! str_contains($function, '::')) { + return self::$effectiveFunctionCache[$function][$actualClassName] = $function; + } + $actualClassName = \is_object($thisOrClass) ? $thisOrClass::class : (\is_string($thisOrClass) ? $thisOrClass : ''); if ($actualClassName === '') { @@ -1022,6 +1072,27 @@ private static function inferTemplatesFromShapes( } } + public static function detectFunctionKind(string $effectiveFunction): int + { + if (! str_contains($effectiveFunction, '::__')) { + return self::KIND_NORMAL; + } + + if (str_ends_with($effectiveFunction, '::__construct')) { + return self::KIND_CONSTRUCT; + } + + if (str_ends_with($effectiveFunction, '::__call') || str_ends_with($effectiveFunction, '::__callStatic')) { + return self::KIND_MAGIC_CALL; + } + + if (str_ends_with($effectiveFunction, '::__get')) { + return self::KIND_MAGIC_GET; + } + + return self::KIND_NORMAL; + } + /** * Traverses shape nodes (including within intersections/unions) and inspects properties or keys. * diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index b5a19658..804ea249 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -29,7 +29,7 @@ final class ReturnChecker /** * Fast O(1) lookup set for generic iterable return types. */ - private const GENERIC_ITERABLES = [ + public const GENERIC_ITERABLES = [ 'iterable' => true, 'traversable' => true, 'iterator' => true, @@ -55,7 +55,7 @@ final class ReturnChecker * * @var array */ - private static array $resolvedStaticReturnCache = []; + public static array $resolvedStaticReturnCache = []; /** * In-memory 2D cache for concrete substituted generic return types: [$function][$templateSignature] => TypeNode. @@ -81,7 +81,7 @@ public static function reset(): void */ public static function isReturnUnconstrained(string $effectiveFunction): bool { - if (str_contains($effectiveFunction, '__call') || str_ends_with($effectiveFunction, '::__get')) { + if ((ParamChecker::$functionKindCache[$effectiveFunction] ??= ParamChecker::detectFunctionKind($effectiveFunction)) >= ParamChecker::KIND_MAGIC_CALL) { return false; } @@ -114,31 +114,26 @@ public static function checkReturn( $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); } - $isMagicCall = str_contains($effectiveFunction, '__call'); - $isMagicGet = str_ends_with($effectiveFunction, '::__get'); + $functionKind = ParamChecker::$functionKindCache[$effectiveFunction] ??= ParamChecker::detectFunctionKind($effectiveFunction); - if (! $isMagicCall && ! $isMagicGet) { - if (isset(self::$noReturnContractCache[$effectiveFunction])) { - return $value; + if ($functionKind === ParamChecker::KIND_MAGIC_CALL) { + $magicResult = self::handleMagicReturn( + $effectiveFunction, + $value, + $thisObj, + $vars, + $registry, + $wrapIterableCallback + ); + + if ($magicResult !== null) { + return $magicResult; } - } - $magicResult = self::handleMagicReturn( - $effectiveFunction, - $value, - $thisObj, - $vars, - $registry, - $wrapIterableCallback - ); - if ($magicResult !== null) { - return $magicResult; - } - if ($isMagicCall) { return $value; } - if ($isMagicGet) { + if ($functionKind === ParamChecker::KIND_MAGIC_GET) { return self::handleMagicPropertyRead( $effectiveFunction, $value, @@ -149,6 +144,10 @@ public static function checkReturn( ); } + if (isset(self::$noReturnContractCache[$effectiveFunction])) { + return $value; + } + $contract ??= DocblockParser::parse($effectiveFunction); if (! ($contract['hasReturnContract'] ?? ($contract['return'] !== null))) { @@ -343,7 +342,8 @@ private static function evaluateReturn( $hasGenerics = (\count($templates) > 0); $hasAliases = (\count($aliases) > 0); - $hasConditionals = ! ($returnTypeNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($returnTypeNode); + $hasConditionals = $contract['returnHasConditional'] + ?? (! ($returnTypeNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($returnTypeNode)); if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && ! ($returnTypeNode instanceof CallableTypeNode)) { $isDynamic = $contract['returnIsDynamic'] ?? (str_contains((string) $returnTypeNode, 'static') || str_contains((string) $returnTypeNode, '$this')); diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index 1d3bed18..bd63e5b4 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -23,6 +23,7 @@ use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Checker\InlineChecker; use TypePHP\Internal\Resolver\HierarchyResolver; use TypePHP\Internal\Resolver\SpecialTypeResolver; @@ -34,6 +35,8 @@ /** * @phpstan-type FunctionContract array{ * types: array, + * constrainedTypes?: array, + * paramConditionals?: array, * paramOuts: array, * selfOut: ?TypeNode, * templates: array, @@ -54,6 +57,7 @@ * returnIsDynamic: bool, * allParamsUnconstrained: bool, * returnUnconstrained: bool, + * returnHasConditional?: bool, * isSimple: bool * } * @@ -301,7 +305,14 @@ private static function isUnconstrainedType(TypeNode $typeNode): bool * @param array $aliases * @param array $methodTemplates * - * @return array{allParamsUnconstrained: bool, returnUnconstrained: bool, isSimple: bool} + * @return array{ + * constrainedTypes: array, + * paramConditionals: array, + * allParamsUnconstrained: bool, + * returnUnconstrained: bool, + * returnHasConditional: bool, + * isSimple: bool + * } */ private static function computeContractFlags( array $types, @@ -312,21 +323,27 @@ private static function computeContractFlags( array $methodTemplates, bool $paramsAreDynamic = false ): array { - $allParamsUnconstrained = true; - if (\count($types) > 0) { - foreach ($types as $tNode) { - if (! self::isUnconstrainedType($tNode)) { - $allParamsUnconstrained = false; + $constrainedTypes = []; + $paramConditionals = []; - break; - } + foreach ($types as $paramName => $tNode) { + if (! ($tNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($tNode)) { + $paramConditionals[$paramName] = true; + $constrainedTypes[$paramName] = $tNode; + } elseif (! self::isUnconstrainedType($tNode)) { + $constrainedTypes[$paramName] = $tNode; } } + $allParamsUnconstrained = ($constrainedTypes === []); + $returnUnconstrained = false; + $returnHasConditional = false; if ($returnType instanceof IdentifierTypeNode) { $lower = strtolower($returnType->name); $returnUnconstrained = ($lower === 'mixed' || $lower === 'array'); + } elseif ($returnType !== null) { + $returnHasConditional = ConditionalChecker::containsConditional($returnType); } $isSimple = ! $paramsUseGenerics @@ -336,8 +353,11 @@ private static function computeContractFlags( && \count($methodTemplates) === 0; return [ + 'constrainedTypes' => $constrainedTypes, + 'paramConditionals' => $paramConditionals, 'allParamsUnconstrained' => $allParamsUnconstrained, 'returnUnconstrained' => $returnUnconstrained, + 'returnHasConditional' => $returnHasConditional, 'isSimple' => $isSimple, ]; } @@ -369,6 +389,8 @@ public static function parse(string $function): array self::parseClassLevelDocs($refClass, $classTemplates, $aliases); $contract = [ 'types' => [], + 'constrainedTypes' => [], + 'paramConditionals' => [], 'paramOuts' => [], 'selfOut' => null, 'templates' => [], @@ -388,12 +410,15 @@ public static function parse(string $function): array 'returnIsDynamic' => false, 'allParamsUnconstrained' => true, 'returnUnconstrained' => false, + 'returnHasConditional' => false, 'isSimple' => true, ]; } } else { $contract = [ 'types' => [], + 'constrainedTypes' => [], + 'paramConditionals' => [], 'paramOuts' => [], 'selfOut' => null, 'templates' => [], @@ -413,6 +438,7 @@ public static function parse(string $function): array 'returnIsDynamic' => false, 'allParamsUnconstrained' => true, 'returnUnconstrained' => false, + 'returnHasConditional' => false, 'isSimple' => true, ]; } @@ -423,6 +449,8 @@ public static function parse(string $function): array } catch (\ReflectionException $e) { $contract = [ 'types' => [], + 'constrainedTypes' => [], + 'paramConditionals' => [], 'paramOuts' => [], 'selfOut' => null, 'templates' => [], @@ -442,6 +470,7 @@ public static function parse(string $function): array 'returnIsDynamic' => false, 'allParamsUnconstrained' => true, 'returnUnconstrained' => false, + 'returnHasConditional' => false, 'isSimple' => true, ]; } @@ -1051,6 +1080,8 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t return [ 'types' => $types, + 'constrainedTypes' => $flags['constrainedTypes'], + 'paramConditionals' => $flags['paramConditionals'], 'paramOuts' => $paramOuts, 'selfOut' => $selfOut, 'templates' => $methodTemplates, @@ -1071,6 +1102,7 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t 'returnIsDynamic' => $returnIsDynamic, 'allParamsUnconstrained' => $flags['allParamsUnconstrained'], 'returnUnconstrained' => $flags['returnUnconstrained'], + 'returnHasConditional' => $flags['returnHasConditional'], 'isSimple' => $flags['isSimple'], ]; } @@ -1109,6 +1141,8 @@ private static function parseFunction(\ReflectionFunction $ref): array if ($doc === false || self::shouldIgnoreDoc($doc)) { return [ 'types' => [], + 'constrainedTypes' => [], + 'paramConditionals' => [], 'paramOuts' => [], 'selfOut' => null, 'templates' => [], @@ -1129,6 +1163,7 @@ private static function parseFunction(\ReflectionFunction $ref): array 'returnIsDynamic' => false, 'allParamsUnconstrained' => true, 'returnUnconstrained' => false, + 'returnHasConditional' => false, 'isSimple' => true, ]; } @@ -1238,6 +1273,8 @@ private static function parseFunction(\ReflectionFunction $ref): array return [ 'types' => $types, + 'constrainedTypes' => $flags['constrainedTypes'], + 'paramConditionals' => $flags['paramConditionals'], 'paramOuts' => $paramOuts, 'selfOut' => null, 'templates' => $templates, @@ -1258,6 +1295,7 @@ private static function parseFunction(\ReflectionFunction $ref): array 'returnIsDynamic' => $returnIsDynamic, 'allParamsUnconstrained' => $flags['allParamsUnconstrained'], 'returnUnconstrained' => $flags['returnUnconstrained'], + 'returnHasConditional' => $flags['returnHasConditional'], 'isSimple' => $flags['isSimple'], ]; } diff --git a/src/Internal/Resolver/CallerBoundaryResolver.php b/src/Internal/Resolver/CallerBoundaryResolver.php index a5caa999..f6e1d5e0 100644 --- a/src/Internal/Resolver/CallerBoundaryResolver.php +++ b/src/Internal/Resolver/CallerBoundaryResolver.php @@ -26,10 +26,19 @@ final class CallerBoundaryResolver */ private static array $callerVendorCache = []; + /** + * Fast-path cache for functions guaranteed not to require boundary bypass + * (either callee is non-vendor, or vendor_boundary_only is disabled). + * + * @var array + */ + public static array $nonBypassCalleeCache = []; + public static function reset(): void { self::$calleeVendorCache = []; self::$callerVendorCache = []; + self::$nonBypassCalleeCache = []; } /** @@ -38,11 +47,13 @@ public static function reset(): void */ public static function shouldBypass(string $function): bool { - if (! Config::isVendorBoundaryOnlyEnabled()) { + if (isset(self::$nonBypassCalleeCache[$function])) { return false; } - if (! self::isCalleeVendor($function)) { + if (! Config::isVendorBoundaryOnlyEnabled() || ! self::isCalleeVendor($function)) { + self::$nonBypassCalleeCache[$function] = true; + return false; } diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 7d15cb33..6e60719f 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -4,9 +4,12 @@ namespace TypePHP\Internal; +use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; +use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Parser\TokenIterator; +use Traversable; use TypePHP\Internal\Ast\ScopeCleaner; use TypePHP\Internal\Checker\GeneratorChecker; use TypePHP\Internal\Checker\InlineChecker; @@ -453,23 +456,25 @@ public static function setupScope(string $function, array $vars, object|string|n $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); - if (CallerBoundaryResolver::shouldBypass($effectiveFunction)) { + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return null; } - if ($thisObj !== null && str_ends_with($effectiveFunction, '::__construct')) { + $functionKind = ParamChecker::$functionKindCache[$effectiveFunction] ??= ParamChecker::detectFunctionKind($effectiveFunction); + + if ($thisObj !== null && $functionKind === ParamChecker::KIND_CONSTRUCT) { TemplateManager::applyPendingInstantiation($thisObj); } - $isMagicCall = str_contains($effectiveFunction, '__call'); - $isMagicGet = str_ends_with($effectiveFunction, '::__get'); - - if ($isMagicGet) { + if ($functionKind === ParamChecker::KIND_MAGIC_GET) { return null; } + $isMagicCall = ($functionKind === ParamChecker::KIND_MAGIC_CALL); + if ( - isset(ParamChecker::$noParamContractCache[$effectiveFunction]) + ! $isMagicCall + && isset(ParamChecker::$noParamContractCache[$effectiveFunction]) && ! (self::$hasMethodTemplatesCache[$effectiveFunction] ?? false) ) { return null; @@ -482,11 +487,44 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } + $registry = self::$registry ??= new TypeValidatorRegistry(); + + if ( + ! $isMagicCall + && $contract['isSimple'] + && ($thisObj !== null || $contract['classTemplates'] === []) + ) { + if ($vars !== []) { + $err = ParamChecker::validateSimpleParams( + $contract['constrainedTypes'] ?? $contract['types'], + $vars, + $effectiveFunction, + $registry, + $contract['sensitiveParams'], + $contract['paramConditionals'] ?? null, + ! isset($contract['constrainedTypes']) + ); + + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return null; + } + + $handled = ViolationCollector::handle($err, 'parameter', null, function: $effectiveFunction); + if ($handled instanceof ErrorMessage) { + return $handled; + } + } + } + + return null; + } + $err = ParamChecker::checkParams( $function, $vars, $thisOrClass, - self::getRegistry(), + $registry, $effectiveFunction, $contract ); @@ -508,16 +546,15 @@ public static function setupScope(string $function, array $vars, object|string|n if ($hasMethodTemplates === null) { $isStaticCall = ($thisObj === null); $hasMethodTemplates = self::$hasMethodTemplatesCache[$effectiveFunction] = ( - (($contract['templates'] ?? []) !== []) - || ($contract['returnUsesMethodTemplates'] ?? false) - || ($isStaticCall && ($contract['classTemplates'] ?? []) !== []) + ($contract['templates'] !== []) + || $contract['returnUsesMethodTemplates'] + || ($isStaticCall && $contract['classTemplates'] !== []) ); } if ($hasMethodTemplates) { $cleaner = new ScopeCleaner($effectiveFunction); - $contract = DocblockParser::parse($effectiveFunction); - $allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; + $allTemplates = [...$contract['classTemplates'], ...$contract['templates']]; $cleaner->boundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $allTemplates); return $cleaner; @@ -645,17 +682,15 @@ public static function checkReturn(string $function, mixed $value, object|string $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); - if (CallerBoundaryResolver::shouldBypass($effectiveFunction)) { + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return $value; } - $isDynamicDispatch = str_contains($effectiveFunction, '::__') - && (str_contains($effectiveFunction, '__call') || str_ends_with($effectiveFunction, '::__get')); + $functionKind = ParamChecker::$functionKindCache[$effectiveFunction] ??= ParamChecker::detectFunctionKind($effectiveFunction); + $isDynamicDispatch = ($functionKind >= ParamChecker::KIND_MAGIC_CALL); - if (! $isDynamicDispatch) { - if (isset(ReturnChecker::$noReturnContractCache[$effectiveFunction])) { - return $value; - } + if (! $isDynamicDispatch && isset(ReturnChecker::$noReturnContractCache[$effectiveFunction])) { + return $value; } $contract = DocblockParser::parse($effectiveFunction); @@ -663,6 +698,55 @@ public static function checkReturn(string $function, mixed $value, object|string return $value; } + $registry = self::$registry ??= new TypeValidatorRegistry(); + $returnTypeNode = $contract['return']; + + if ( + ! $isDynamicDispatch + && $returnTypeNode !== null + && $contract['isSimple'] + && $contract['classTemplates'] === [] + && ! ($contract['returnHasConditional'] ?? true) + && ! $contract['returnIsDynamic'] + && ! ($returnTypeNode instanceof CallableTypeNode) + ) { + $resolvedType = ReturnChecker::$resolvedStaticReturnCache[$effectiveFunction] + ??= SpecialTypeResolver::resolve($returnTypeNode, $effectiveFunction, null); + + if ($resolvedType instanceof IdentifierTypeNode) { + $lowerName = strtolower($resolvedType->name); + if ($lowerName === 'mixed' || $lowerName === 'array') { + return $value; + } + } + + $err = $registry->validate($value, $resolvedType, 'Return value'); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + $formattedErr = ErrorFactory::createError($effectiveFunction . '(): ' . $err->getMessage()); + + return ViolationCollector::handle($formattedErr, 'return', $value, function: $effectiveFunction, target: 'return'); + } + + if ($value instanceof Traversable) { + $baseName = ''; + if ($resolvedType instanceof IdentifierTypeNode) { + $baseName = strtolower(ltrim($resolvedType->name, '\\')); + } elseif ($resolvedType instanceof GenericTypeNode) { + $baseName = strtolower(ltrim((string) $resolvedType->type, '\\')); + } + + if (isset(ReturnChecker::GENERIC_ITERABLES[$baseName])) { + return self::wrapIterable($effectiveFunction, 'return', $value); + } + } + + return $value; + } + $vars = $vars !== null ? $vars : []; $res = ReturnChecker::checkReturn( @@ -670,7 +754,7 @@ public static function checkReturn(string $function, mixed $value, object|string $value, $thisOrClass, $vars, - self::getRegistry(), + $registry, [self::class, 'wrapIterable'], $effectiveFunction, $contract diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index 399dd2fc..c0463091 100644 --- a/src/Internal/Util/Config.php +++ b/src/Internal/Util/Config.php @@ -103,6 +103,14 @@ final class Config private static int $ignoreTraceDepth = 25; + private static bool $processEnvProbed = false; + + private static ?string $processEnvDisable = null; + + private static ?string $processEnvEnabled = null; + + private static bool $hasProcessEnvOverride = false; + private static function getEnvValue(string $key): ?string { if (isset($_ENV[$key])) { @@ -131,25 +139,26 @@ private static function getEnvValue(string $key): ?string public static function isEnabled(): bool { - // Hot path: called by every runtime check. The overrides are re-probed on each call - // (Dotenv may populate them after boot), but only resolved when one is actually present. + if (! self::$processEnvProbed) { + self::probeProcessEnvOverrides(); + } + if ( - isset($_ENV['TYPEPHP_DISABLE']) + self::$hasProcessEnvOverride + || isset($_ENV['TYPEPHP_DISABLE']) || isset($_SERVER['TYPEPHP_DISABLE']) || isset($_ENV['TYPEPHP_ENABLED']) || isset($_SERVER['TYPEPHP_ENABLED']) - || getenv('TYPEPHP_DISABLE') !== false - || getenv('TYPEPHP_ENABLED') !== false || \defined('TYPEPHP_DISABLE') ) { - $envDisable = self::getEnvValue('TYPEPHP_DISABLE'); + $envDisable = self::resolveEnabledOverride('TYPEPHP_DISABLE', self::$processEnvDisable); if ($envDisable !== null && trim($envDisable) !== '') { if (filter_var($envDisable, FILTER_VALIDATE_BOOLEAN)) { return false; } } - $envEnabled = self::getEnvValue('TYPEPHP_ENABLED'); + $envEnabled = self::resolveEnabledOverride('TYPEPHP_ENABLED', self::$processEnvEnabled); if ($envEnabled !== null && trim($envEnabled) !== '') { if (! filter_var($envEnabled, FILTER_VALIDATE_BOOLEAN)) { return false; @@ -859,6 +868,10 @@ public static function reset(): void self::$inlineScalars = true; self::$inlineArrays = true; self::$inlineObjects = true; + self::$processEnvProbed = false; + self::$processEnvDisable = null; + self::$processEnvEnabled = null; + self::$hasProcessEnvOverride = false; DocblockParser::reset(); ParamChecker::reset(); @@ -935,4 +948,36 @@ private static function syncFlags(array $config): void self::$inlineArrays = (bool) ($inline['arrays'] ?? true); self::$inlineObjects = (bool) ($inline['objects'] ?? true); } + + private static function probeProcessEnvOverrides(): void + { + $disable = getenv('TYPEPHP_DISABLE'); + $enabled = getenv('TYPEPHP_ENABLED'); + + self::$processEnvDisable = $disable !== false ? $disable : null; + self::$processEnvEnabled = $enabled !== false ? $enabled : null; + self::$hasProcessEnvOverride = self::$processEnvDisable !== null || self::$processEnvEnabled !== null; + self::$processEnvProbed = true; + } + + private static function resolveEnabledOverride(string $key, ?string $cachedProcessEnv): ?string + { + if (isset($_ENV[$key])) { + $val = $_ENV[$key]; + } elseif (isset($_SERVER[$key])) { + $val = $_SERVER[$key]; + } else { + return $cachedProcessEnv; + } + + if (\is_string($val)) { + return $val; + } + + if (\is_scalar($val)) { + return (string) $val; + } + + return null; + } } diff --git a/src/Internal/Validator/ArrayShapeValidator.php b/src/Internal/Validator/ArrayShapeValidator.php index 58cbf4bb..cbec95dd 100644 --- a/src/Internal/Validator/ArrayShapeValidator.php +++ b/src/Internal/Validator/ArrayShapeValidator.php @@ -12,12 +12,27 @@ use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; +use WeakMap; /** * @internal Class for validating array shapes and tuple shapes like array{0: string, 1: int} or array{string, int}. */ final class ArrayShapeValidator implements TypeValidatorInterface { + /** + * Compiled shape metadata cached per ArrayShapeNode instance. + * + * @var WeakMap, + * knownKeys: array, + * unsealedKeyType: ?TypeNode, + * unsealedValueType: ?TypeNode + * }>|null + */ + private static ?WeakMap $compiledShapeCache = null; + public function validate(mixed $value, TypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { if (! \is_array($value)) { @@ -27,35 +42,18 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali /** @var ArrayShapeNode $shapeNode */ $shapeNode = $node; - if ($shapeNode->kind === ArrayShapeNode::KIND_LIST && \count($value) > 0 && ! array_is_list($value)) { + self::$compiledShapeCache ??= new WeakMap(); + $compiled = self::$compiledShapeCache[$shapeNode] ??= self::compileShape($shapeNode); + + if ($compiled['isList'] && $value !== [] && ! array_is_list($value)) { return ErrorFactory::createError($context . ' must be a list, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } - $knownKeys = []; - $nextAutoIndex = 0; $matchedKeysCount = 0; - foreach ($shapeNode->items as $item) { - $key = null; - - if ($item->keyName instanceof ConstExprStringNode) { - $key = $item->keyName->value; - } elseif ($item->keyName instanceof ConstExprIntegerNode) { - $key = (int) $item->keyName->value; - $nextAutoIndex = max($nextAutoIndex, $key + 1); - } elseif ($item->keyName instanceof IdentifierTypeNode) { - $key = $item->keyName->name; - } elseif ($item->keyName !== null) { - $key = (string) $item->keyName; - } else { - $key = $nextAutoIndex; - $nextAutoIndex++; - } - - $knownKeys[$key] = true; - + foreach ($compiled['items'] as [$key, $optional, $valueType]) { if (! \array_key_exists($key, $value)) { - if (! $item->optional) { + if (! $optional) { return ErrorFactory::createError($context . " is missing required key '$key'"); } @@ -64,7 +62,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali $matchedKeysCount++; - $err = $registry->validate($value[$key], $item->valueType, '', $isSensitive); + $err = $registry->validate($value[$key], $valueType, '', $isSensitive); if ($err !== null) { return ErrorFactory::createError($context . "['" . $key . "']" . $err->getMessage()); } @@ -76,7 +74,9 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return null; } - if ($shapeNode->sealed) { + $knownKeys = $compiled['knownKeys']; + + if ($compiled['sealed']) { foreach ($value as $k => $_) { if (! isset($knownKeys[$k])) { return ErrorFactory::createError($context . " contains unsealed unexpected key '{$k}'"); @@ -84,9 +84,9 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali } } - if ($shapeNode->unsealedType !== null) { - $unsealedKeyType = $shapeNode->unsealedType->keyType; - $unsealedValueType = $shapeNode->unsealedType->valueType; + if ($compiled['unsealedValueType'] !== null) { + $unsealedKeyType = $compiled['unsealedKeyType']; + $unsealedValueType = $compiled['unsealedValueType']; foreach ($value as $k => $v) { if (isset($knownKeys[$k])) { @@ -109,4 +109,49 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return null; } -} + + /** + * @return array{ + * isList: bool, + * sealed: bool, + * items: list, + * knownKeys: array, + * unsealedKeyType: ?TypeNode, + * unsealedValueType: ?TypeNode + * } + */ + private static function compileShape(ArrayShapeNode $shapeNode): array + { + $items = []; + $knownKeys = []; + $nextAutoIndex = 0; + + foreach ($shapeNode->items as $item) { + if ($item->keyName instanceof ConstExprStringNode) { + $key = $item->keyName->value; + } elseif ($item->keyName instanceof ConstExprIntegerNode) { + $key = (int) $item->keyName->value; + $nextAutoIndex = max($nextAutoIndex, $key + 1); + } elseif ($item->keyName instanceof IdentifierTypeNode) { + $key = $item->keyName->name; + } elseif ($item->keyName !== null) { + $key = (string) $item->keyName; + } else { + $key = $nextAutoIndex; + $nextAutoIndex++; + } + + $knownKeys[$key] = true; + $items[] = [$key, $item->optional, $item->valueType]; + } + + return [ + 'isList' => $shapeNode->kind === ArrayShapeNode::KIND_LIST, + 'sealed' => $shapeNode->sealed, + 'items' => $items, + 'knownKeys' => $knownKeys, + 'unsealedKeyType' => $shapeNode->unsealedType?->keyType, + 'unsealedValueType' => $shapeNode->unsealedType?->valueType, + ]; + } +} \ No newline at end of file diff --git a/src/Internal/Validator/CollectionElementValidator.php b/src/Internal/Validator/CollectionElementValidator.php index ca0595a7..35217738 100644 --- a/src/Internal/Validator/CollectionElementValidator.php +++ b/src/Internal/Validator/CollectionElementValidator.php @@ -35,18 +35,14 @@ public static function validateElements( return null; } - if ($elementTypeNode instanceof IdentifierTypeNode && \in_array(strtolower($elementTypeNode->name), ['mixed', 't', 'tvalue', 'v', 'value', 'telement'], true)) { - return null; - } - - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { - return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); - } - if ($elementTypeNode instanceof IdentifierTypeNode) { $elemName = $elementTypeNode->name; if ($elemName === 'int') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + foreach ($items as $k => $v) { if (! \is_int($v)) { return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type int, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); @@ -57,6 +53,10 @@ public static function validateElements( } if ($elemName === 'positive-int') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + foreach ($items as $k => $v) { if (! \is_int($v) || $v <= 0) { return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type positive-int, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); @@ -67,6 +67,10 @@ public static function validateElements( } if ($elemName === 'string') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + foreach ($items as $k => $v) { if (! \is_string($v)) { return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type string, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); @@ -77,6 +81,10 @@ public static function validateElements( } if ($elemName === 'non-empty-string') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + foreach ($items as $k => $v) { if (! \is_string($v) || $v === '') { return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type non-empty-string, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); @@ -87,6 +95,10 @@ public static function validateElements( } if ($elemName === 'bool') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + foreach ($items as $k => $v) { if (! \is_bool($v)) { return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type bool, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); @@ -97,6 +109,10 @@ public static function validateElements( } if ($elemName === 'float') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + foreach ($items as $k => $v) { if (! \is_float($v) && ! \is_int($v)) { return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type float, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); @@ -105,6 +121,14 @@ public static function validateElements( return null; } + + if (\in_array(strtolower($elemName), ['mixed', 't', 'tvalue', 'v', 'value', 'telement'], true)) { + return null; + } + } + + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } foreach ($items as $k => $v) { diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index b6c62f91..39bda670 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -82,13 +82,18 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali { /** @var GenericTypeNode $genericNode */ $genericNode = $node; - $baseType = strtolower((string) $genericNode->type); + $typeName = $genericNode->type instanceof IdentifierTypeNode + ? $genericNode->type->name + : (string) $genericNode->type; + $baseType = strtolower($typeName); return match ($baseType) { 'int', 'integer' => $this->validateIntRange($value, $genericNode, $context, $isSensitive), 'class-string' => $this->validateClassString($value, $genericNode, $context, $isSensitive), - 'list', 'non-empty-list', 'non-empty-array-list' => $this->validateList($value, $genericNode, $context, $registry, $isSensitive), - 'array', 'non-empty-array', 'iterable', 'traversable', 'generator', 'iterator' => $this->validateArray($value, $genericNode, $context, $registry, $isSensitive), + 'list' => $this->validateList($value, $genericNode, $context, $registry, $isSensitive, false), + 'non-empty-list', 'non-empty-array-list' => $this->validateList($value, $genericNode, $context, $registry, $isSensitive, true), + 'array', 'iterable', 'traversable', 'generator', 'iterator' => $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, false), + 'non-empty-array' => $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, true), 'key-of' => $this->validateKeyOf($value, $genericNode, $context, $registry, $isSensitive), 'value-of' => $this->validateValueOf($value, $genericNode, $context, $registry, $isSensitive), 'int-mask' => $this->validateIntMask($value, $genericNode, $context, $isSensitive), @@ -496,17 +501,15 @@ private function resolveMaskOfPattern(string $className, string $pattern): array return self::$maskOfCache[$cacheKey] = [$allowedMask, $foundFlags]; } - private function validateList(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage + private function validateList(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false, bool $requireNonEmpty = false): ?ErrorMessage { - $baseType = strtolower((string) $node->type); - - if (! \is_array($value) || (\count($value) > 0 && ! array_is_list($value))) { + if (! \is_array($value) || ($value !== [] && ! array_is_list($value))) { return ErrorFactory::createError($context . ' must be a list, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } $count = \count($value); - if (str_contains($baseType, 'non-empty') && $count === 0) { + if ($requireNonEmpty && $count === 0) { return ErrorFactory::createError($context . ' must be a non-empty list, empty array given'); } @@ -526,10 +529,8 @@ private function validateList(mixed $value, GenericTypeNode $node, string $conte ); } - private function validateArray(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage + private function validateArray(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false, bool $requireNonEmpty = false): ?ErrorMessage { - $baseType = strtolower((string) $node->type); - if (! \is_array($value) && ! ($value instanceof \Traversable)) { return ErrorFactory::createError($context . ' must be of type ' . (string) $node->type . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } @@ -540,7 +541,7 @@ private function validateArray(mixed $value, GenericTypeNode $node, string $cont $count = \count($value); - if (str_contains($baseType, 'non-empty') && $count === 0) { + if ($requireNonEmpty && $count === 0) { return ErrorFactory::createError($context . ' must be a non-empty array, empty array given'); } diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index fbf1bc92..76641320 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -87,6 +87,24 @@ public function __construct() public function validate(mixed $value, TypeNode $node, string $context = '', bool $isSensitive = false): ?ErrorMessage { if ($node instanceof IdentifierTypeNode) { + $ok = match ($node->name) { + 'int' => \is_int($value), + 'string' => \is_string($value), + 'positive-int' => \is_int($value) && $value > 0, + 'non-empty-string' => \is_string($value) && $value !== '', + 'bool' => \is_bool($value), + 'float' => \is_float($value) || \is_int($value), + 'array-key' => \is_int($value) || \is_string($value), + 'array' => \is_array($value), + 'mixed' => true, + 'null' => $value === null, + default => false, + }; + + if ($ok) { + return null; + } + return $this->identifierValidator->validate($value, $node, $context, $this, $isSensitive); } diff --git a/src/Internal/Validator/UnionValidator.php b/src/Internal/Validator/UnionValidator.php index 918bb1c3..4144c3cd 100644 --- a/src/Internal/Validator/UnionValidator.php +++ b/src/Internal/Validator/UnionValidator.php @@ -4,8 +4,11 @@ namespace TypePHP\Internal\Validator; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode; 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\Type\ArrayShapeNode; use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; @@ -17,17 +20,59 @@ use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Util\ClassNameValidator; +use WeakMap; /** * @internal Class for validating union types like int | string. */ final class UnionValidator implements TypeValidatorInterface { + /** + * Compiled primitive & literal fast-path sets cached per UnionTypeNode. + * + * @var WeakMap, + * intLiterals: array + * }>|null + */ + private static ?WeakMap $compiledUnionCache = null; + public function validate(mixed $value, TypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { /** @var UnionTypeNode $unionNode */ $unionNode = $node; + self::$compiledUnionCache ??= new WeakMap(); + $compiled = self::$compiledUnionCache[$unionNode] ??= self::compileUnion($unionNode); + + if ($value === null && $compiled['hasNull']) { + return null; + } + + if (\is_int($value) && ($compiled['hasInt'] || isset($compiled['intLiterals'][$value]))) { + return null; + } + + if (\is_string($value) && ($compiled['hasString'] || isset($compiled['stringLiterals'][$value]) || ($compiled['hasClassString'] && ClassNameValidator::isValidClassString($value)))) { + return null; + } + + if (\is_bool($value) && ($compiled['hasBool'] || ($value ? $compiled['hasTrue'] : $compiled['hasFalse']))) { + return null; + } + + if (\is_object($value) && $compiled['hasObject']) { + return null; + } + foreach ($unionNode->types as $type) { if ($type instanceof IdentifierTypeNode) { $name = $type->name; @@ -188,4 +233,99 @@ private static function checkDiscriminatorStatus(mixed $value, TypeNode $type): return ['hasDiscriminator' => false, 'isMatched' => false]; } + + /** + * @return array{ + * hasObject: bool, + * hasInt: bool, + * hasString: bool, + * hasBool: bool, + * hasNull: bool, + * hasTrue: bool, + * hasFalse: bool, + * hasClassString: bool, + * stringLiterals: array, + * intLiterals: array + * } + */ + private static function compileUnion(UnionTypeNode $unionNode): array + { + $hasObject = false; + $hasInt = false; + $hasString = false; + $hasBool = false; + $hasNull = false; + $hasTrue = false; + $hasFalse = false; + $hasClassString = false; + $stringLiterals = []; + $intLiterals = []; + + foreach ($unionNode->types as $type) { + if ($type instanceof IdentifierTypeNode) { + switch (strtolower($type->name)) { + case 'object': + $hasObject = true; + + break; + case 'int': + case 'integer': + $hasInt = true; + + break; + case 'string': + $hasString = true; + + break; + case 'bool': + case 'boolean': + $hasBool = true; + + break; + case 'null': + $hasNull = true; + + break; + case 'true': + $hasTrue = true; + + break; + case 'false': + $hasFalse = true; + + break; + case 'class-string': + $hasClassString = true; + + break; + } + } elseif ($type instanceof ConstTypeNode) { + $constExpr = $type->constExpr; + if ($constExpr instanceof ConstExprStringNode) { + $stringLiterals[$constExpr->value] = true; + } elseif ($constExpr instanceof ConstExprIntegerNode) { + $intLiterals[(int) $constExpr->value] = true; + } elseif ($constExpr instanceof ConstExprTrueNode) { + $hasTrue = true; + } elseif ($constExpr instanceof ConstExprFalseNode) { + $hasFalse = true; + } elseif ($constExpr instanceof ConstExprNullNode) { + $hasNull = true; + } + } + } + + return [ + 'hasObject' => $hasObject, + 'hasInt' => $hasInt, + 'hasString' => $hasString, + 'hasBool' => $hasBool, + 'hasNull' => $hasNull, + 'hasTrue' => $hasTrue, + 'hasFalse' => $hasFalse, + 'hasClassString' => $hasClassString, + 'stringLiterals' => $stringLiterals, + 'intLiterals' => $intLiterals, + ]; + } } diff --git a/tests/Internal/Util/ConfigTest.php b/tests/Internal/Util/ConfigTest.php index eda0d5bb..9d21128b 100644 --- a/tests/Internal/Util/ConfigTest.php +++ b/tests/Internal/Util/ConfigTest.php @@ -313,19 +313,23 @@ function cleanTypePhpEnvVariables(): void unset($_SERVER['TYPEPHP_ENABLED']); }); - test('isEnabled dynamically reflects TYPEPHP_DISABLE and TYPEPHP_ENABLED set through putenv()', function () { + test('isEnabled reflects TYPEPHP_DISABLE and TYPEPHP_ENABLED set through putenv() after reset', function () { expect(Config::isEnabled())->toBeTrue(); putenv('TYPEPHP_DISABLE=1'); + Config::reset(); expect(Config::isEnabled())->toBeFalse(); putenv('TYPEPHP_DISABLE'); + Config::reset(); expect(Config::isEnabled())->toBeTrue(); putenv('TYPEPHP_ENABLED=false'); + Config::reset(); expect(Config::isEnabled())->toBeFalse(); putenv('TYPEPHP_ENABLED'); + Config::reset(); expect(Config::isEnabled())->toBeTrue(); }); From 5b41093dea6a6d1112eed3534d961f90dedbecc5 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 17 Nov 2026 13:23:38 +0800 Subject: [PATCH 02/25] Optimized ArrayShapeValidator --- .../Validator/ArrayShapeValidator.php | 271 +++++++++++++++++- .../Validator/TypeValidatorRegistry.php | 1 + 2 files changed, 260 insertions(+), 12 deletions(-) diff --git a/src/Internal/Validator/ArrayShapeValidator.php b/src/Internal/Validator/ArrayShapeValidator.php index cbec95dd..664a8bc2 100644 --- a/src/Internal/Validator/ArrayShapeValidator.php +++ b/src/Internal/Validator/ArrayShapeValidator.php @@ -4,14 +4,21 @@ namespace TypePHP\Internal\Validator; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode; 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\Type\ArrayShapeNode; +use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; +use TypePHP\Internal\Util\ClassNameValidator; use WeakMap; /** @@ -19,13 +26,62 @@ */ final class ArrayShapeValidator implements TypeValidatorInterface { + private const CHECK_FALLBACK = 0; + + private const CHECK_INT = 1; + + private const CHECK_STRING = 2; + + private const CHECK_BOOL = 3; + + private const CHECK_FLOAT = 4; + + private const CHECK_POSITIVE_INT = 5; + + private const CHECK_NEGATIVE_INT = 6; + + private const CHECK_NON_POSITIVE_INT = 7; + + private const CHECK_NON_NEGATIVE_INT = 8; + + private const CHECK_NON_ZERO_INT = 9; + + private const CHECK_NON_EMPTY_STRING = 10; + private const CHECK_ARRAY_KEY = 11; + + private const CHECK_ARRAY = 12; + + private const CHECK_LIST = 13; + + private const CHECK_MIXED = 14; + + private const CHECK_NULL = 15; + + private const CHECK_TRUE = 16; + + private const CHECK_FALSE = 17; + + private const CHECK_SCALAR = 18; + + private const CHECK_INT_OR_STRING = 19; + + private const CHECK_EXACT_STRING = 20; + + private const CHECK_EXACT_INT = 21; + + private const CHECK_STRING_MAP = 22; + + private const CHECK_INT_MAP = 23; + + private const CHECK_CLASS = 24; + /** * Compiled shape metadata cached per ArrayShapeNode instance. * * @var WeakMap, + * items: list, * knownKeys: array, * unsealedKeyType: ?TypeNode, * unsealedValueType: ?TypeNode @@ -33,6 +89,11 @@ final class ArrayShapeValidator implements TypeValidatorInterface */ private static ?WeakMap $compiledShapeCache = null; + public static function reset(): void + { + self::$compiledShapeCache = null; + } + public function validate(mixed $value, TypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { if (! \is_array($value)) { @@ -42,8 +103,14 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali /** @var ArrayShapeNode $shapeNode */ $shapeNode = $node; - self::$compiledShapeCache ??= new WeakMap(); - $compiled = self::$compiledShapeCache[$shapeNode] ??= self::compileShape($shapeNode); + if (self::$compiledShapeCache === null) { + self::$compiledShapeCache = new WeakMap(); + } + + $compiled = self::$compiledShapeCache[$shapeNode] ?? null; + if ($compiled === null) { + self::$compiledShapeCache[$shapeNode] = $compiled = self::compileShape($shapeNode); + } if ($compiled['isList'] && $value !== [] && ! array_is_list($value)) { return ErrorFactory::createError($context . ' must be a list, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); @@ -51,18 +118,60 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali $matchedKeysCount = 0; - foreach ($compiled['items'] as [$key, $optional, $valueType]) { - if (! \array_key_exists($key, $value)) { - if (! $optional) { - return ErrorFactory::createError($context . " is missing required key '$key'"); + foreach ($compiled['items'] as $item) { + $key = $item[0]; + + if (isset($value[$key])) { + $v = $value[$key]; + } elseif (\array_key_exists($key, $value)) { + $v = null; + } else { + if ($item[1]) { + continue; } - continue; + return ErrorFactory::createError($context . " is missing required key '$key'"); } $matchedKeysCount++; - $err = $registry->validate($value[$key], $valueType, '', $isSensitive); + if ($item[5] && $v === null) { + continue; + } + + $ok = match ($item[3]) { + self::CHECK_INT => \is_int($v), + self::CHECK_STRING => \is_string($v), + self::CHECK_POSITIVE_INT => \is_int($v) && $v > 0, + self::CHECK_NON_EMPTY_STRING => \is_string($v) && $v !== '', + self::CHECK_BOOL => \is_bool($v), + self::CHECK_ARRAY_KEY => \is_int($v) || \is_string($v), + self::CHECK_FLOAT => \is_float($v) || \is_int($v), + self::CHECK_ARRAY => \is_array($v), + self::CHECK_LIST => \is_array($v) && ($v === [] || array_is_list($v)), + self::CHECK_EXACT_STRING => \is_string($v) && $v === $item[4], + self::CHECK_STRING_MAP => \is_string($v) && isset($item[4][$v]), + self::CHECK_EXACT_INT => \is_int($v) && $v === $item[4], + self::CHECK_INT_MAP => \is_int($v) && isset($item[4][$v]), + self::CHECK_INT_OR_STRING => \is_int($v) || \is_string($v), + self::CHECK_TRUE => $v === true, + self::CHECK_FALSE => $v === false, + self::CHECK_NULL => $v === null, + self::CHECK_MIXED => true, + self::CHECK_SCALAR => \is_scalar($v), + self::CHECK_CLASS => \is_object($v) && is_a($v, $item[4]), + self::CHECK_NEGATIVE_INT => \is_int($v) && $v < 0, + self::CHECK_NON_NEGATIVE_INT => \is_int($v) && $v >= 0, + self::CHECK_NON_POSITIVE_INT => \is_int($v) && $v <= 0, + self::CHECK_NON_ZERO_INT => \is_int($v) && $v !== 0, + default => false, + }; + + if ($ok) { + continue; + } + + $err = $registry->validate($v, $item[2], '', $isSensitive); if ($err !== null) { return ErrorFactory::createError($context . "['" . $key . "']" . $err->getMessage()); } @@ -114,7 +223,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali * @return array{ * isList: bool, * sealed: bool, - * items: list, + * items: list, * knownKeys: array, * unsealedKeyType: ?TypeNode, * unsealedValueType: ?TypeNode @@ -142,7 +251,8 @@ private static function compileShape(ArrayShapeNode $shapeNode): array } $knownKeys[$key] = true; - $items[] = [$key, $item->optional, $item->valueType]; + [$checkKind, $checkData, $nullable] = self::compileItemType($item->valueType); + $items[] = [$key, $item->optional, $item->valueType, $checkKind, $checkData, $nullable]; } return [ @@ -154,4 +264,141 @@ private static function compileShape(ArrayShapeNode $shapeNode): array 'unsealedValueType' => $shapeNode->unsealedType?->valueType, ]; } -} \ No newline at end of file + + /** + * @return array{0: int, 1: mixed, 2: bool} [checkKind, checkData, nullable] + */ + private static function compileItemType(TypeNode $typeNode): array + { + if ($typeNode instanceof NullableTypeNode) { + [$check, $data] = self::compileItemType($typeNode->type); + + return [$check, $data, true]; + } + + if ($typeNode instanceof ConstTypeNode) { + $expr = $typeNode->constExpr; + if ($expr instanceof ConstExprStringNode) { + return [self::CHECK_EXACT_STRING, $expr->value, false]; + } + if ($expr instanceof ConstExprIntegerNode) { + return [self::CHECK_EXACT_INT, (int) $expr->value, false]; + } + if ($expr instanceof ConstExprTrueNode) { + return [self::CHECK_TRUE, null, false]; + } + if ($expr instanceof ConstExprFalseNode) { + return [self::CHECK_FALSE, null, false]; + } + if ($expr instanceof ConstExprNullNode) { + return [self::CHECK_NULL, null, true]; + } + + return [self::CHECK_FALLBACK, null, false]; + } + + if ($typeNode instanceof IdentifierTypeNode) { + $name = $typeNode->name; + $lower = strtolower($name); + + return match ($lower) { + 'int', 'integer' => [self::CHECK_INT, null, false], + 'string' => [self::CHECK_STRING, null, false], + 'bool', 'boolean' => [self::CHECK_BOOL, null, false], + 'float', 'double' => [self::CHECK_FLOAT, null, false], + 'positive-int' => [self::CHECK_POSITIVE_INT, null, false], + 'negative-int' => [self::CHECK_NEGATIVE_INT, null, false], + 'non-positive-int' => [self::CHECK_NON_POSITIVE_INT, null, false], + 'non-negative-int', 'unsigned-int' => [self::CHECK_NON_NEGATIVE_INT, null, false], + 'non-zero-int' => [self::CHECK_NON_ZERO_INT, null, false], + 'non-empty-string' => [self::CHECK_NON_EMPTY_STRING, null, false], + 'array-key' => [self::CHECK_ARRAY_KEY, null, false], + 'array' => [self::CHECK_ARRAY, null, false], + 'list' => [self::CHECK_LIST, null, false], + 'mixed' => [self::CHECK_MIXED, null, false], + 'null' => [self::CHECK_NULL, null, true], + 'true' => [self::CHECK_TRUE, null, false], + 'false' => [self::CHECK_FALSE, null, false], + 'scalar' => [self::CHECK_SCALAR, null, false], + default => (ClassNameValidator::isValid($name) && (class_exists($name, false) || interface_exists($name, false))) + ? [self::CHECK_CLASS, $name, false] + : [self::CHECK_FALLBACK, null, false], + }; + } + + if ($typeNode instanceof UnionTypeNode) { + $nullable = false; + $nonNullMembers = []; + + foreach ($typeNode->types as $member) { + if ($member instanceof NullableTypeNode) { + $nullable = true; + $nonNullMembers[] = $member->type; + } elseif ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'null') { + $nullable = true; + } elseif ($member instanceof ConstTypeNode && $member->constExpr instanceof ConstExprNullNode) { + $nullable = true; + } else { + $nonNullMembers[] = $member; + } + } + + if (\count($nonNullMembers) === 1) { + [$innerCheck, $innerData] = self::compileItemType($nonNullMembers[0]); + + return [$innerCheck, $innerData, $nullable]; + } + + if (\count($nonNullMembers) === 2) { + $t0 = $nonNullMembers[0]; + $t1 = $nonNullMembers[1]; + if ($t0 instanceof IdentifierTypeNode && $t1 instanceof IdentifierTypeNode) { + $n0 = strtolower($t0->name); + $n1 = strtolower($t1->name); + if (($n0 === 'int' || $n0 === 'integer') && $n1 === 'string') { + return [self::CHECK_INT_OR_STRING, null, $nullable]; + } + if ($n0 === 'string' && ($n1 === 'int' || $n1 === 'integer')) { + return [self::CHECK_INT_OR_STRING, null, $nullable]; + } + } + } + + $allStrings = true; + $stringMap = []; + foreach ($nonNullMembers as $member) { + if ($member instanceof ConstTypeNode && $member->constExpr instanceof ConstExprStringNode) { + $stringMap[$member->constExpr->value] = true; + } else { + $allStrings = false; + + break; + } + } + + if ($allStrings && $stringMap !== []) { + return [self::CHECK_STRING_MAP, $stringMap, $nullable]; + } + + $allInts = true; + $intMap = []; + foreach ($nonNullMembers as $member) { + if ($member instanceof ConstTypeNode && $member->constExpr instanceof ConstExprIntegerNode) { + $intMap[(int) $member->constExpr->value] = true; + } else { + $allInts = false; + + break; + } + } + + if ($allInts && $intMap !== []) { + return [self::CHECK_INT_MAP, $intMap, $nullable]; + } + + return [self::CHECK_FALLBACK, null, $nullable]; + } + + return [self::CHECK_FALLBACK, null, false]; + } +} diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index 76641320..62eb13f9 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -52,6 +52,7 @@ final class TypeValidatorRegistry public static function reset(): void { GenericValidator::reset(); + ArrayShapeValidator::reset(); } public function __construct() From e196d93aa9e87eb16ff5777c08cff8844e7749d6 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 17 Nov 2026 15:45:31 +0800 Subject: [PATCH 03/25] Enhance RuntimeTypeChecker and ParamChecker with new configuration options and optimizations --- src/Internal/Checker/ParamChecker.php | 65 +++-- src/Internal/RuntimeTypeChecker.php | 116 ++++++++- src/Internal/Util/Config.php | 14 +- .../Validator/ArrayShapeValidator.php | 2 +- src/Internal/Validator/GenericValidator.php | 231 ++++++++++++------ .../Validator/TypeValidatorRegistry.php | 75 ++++-- 6 files changed, 357 insertions(+), 146 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 49128d2e..f9e04450 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -344,29 +344,38 @@ public static function validateSimpleParams( ?array $paramConditionals = null, bool $filterUnconstrained = false ): ?ErrorMessage { + $hasSensitive = $sensitiveParams !== []; + $hasConditionals = $paramConditionals !== null && $paramConditionals !== []; + foreach ($types as $paramName => $typeNode) { - if (isset($vars[$paramName]) || \array_key_exists($paramName, $vars)) { - if ($paramConditionals === null) { - if (! ($typeNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($typeNode)) { - $typeNode = ConditionalChecker::resolve($typeNode, $vars, [], $registry, $effectiveFunction); - if (self::isUnconstrained($typeNode)) { - continue; - } - } elseif ($filterUnconstrained && self::isUnconstrained($typeNode)) { - continue; - } - } elseif (isset($paramConditionals[$paramName])) { + if (isset($vars[$paramName])) { + $val = $vars[$paramName]; + } elseif (\array_key_exists($paramName, $vars)) { + $val = null; + } else { + continue; + } + + if ($hasConditionals && isset($paramConditionals[$paramName])) { + $typeNode = ConditionalChecker::resolve($typeNode, $vars, [], $registry, $effectiveFunction); + if (self::isUnconstrained($typeNode)) { + continue; + } + } elseif ($paramConditionals === null) { + if (! ($typeNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($typeNode)) { $typeNode = ConditionalChecker::resolve($typeNode, $vars, [], $registry, $effectiveFunction); if (self::isUnconstrained($typeNode)) { continue; } + } elseif ($filterUnconstrained && self::isUnconstrained($typeNode)) { + continue; } + } - $isSensitive = $sensitiveParams[$paramName] ?? false; - $err = $registry->validate($vars[$paramName], $typeNode, '', $isSensitive); - if ($err !== null) { - return ErrorFactory::createError($effectiveFunction . '(): Argument $' . $paramName . $err->getMessage()); - } + $isSensitive = $hasSensitive && ($sensitiveParams[$paramName] ?? false); + $err = $registry->validate($val, $typeNode, '', $isSensitive); + if ($err !== null) { + return ErrorFactory::createError($effectiveFunction . '(): Argument $' . $paramName . $err->getMessage()); } } @@ -547,28 +556,18 @@ public static function resolveEffectiveFunction(string $function, object|string| return $function; } - if (isset(self::$effectiveFunctionCache[$function][$actualClassName])) { - return self::$effectiveFunctionCache[$function][$actualClassName]; + if (isset(self::$effectiveFunctionCache[$actualClassName][$function])) { + return self::$effectiveFunctionCache[$actualClassName][$function]; } if (! str_contains($function, '::')) { - return self::$effectiveFunctionCache[$function][$actualClassName] = $function; - } - - $actualClassName = \is_object($thisOrClass) ? $thisOrClass::class : (\is_string($thisOrClass) ? $thisOrClass : ''); - - if ($actualClassName === '') { - return $function; - } - - if (isset(self::$effectiveFunctionCache[$function][$actualClassName])) { - return self::$effectiveFunctionCache[$function][$actualClassName]; + return self::$effectiveFunctionCache[$actualClassName][$function] = $function; } $traitAliases = HierarchyResolver::getTraitAliases($actualClassName); - if (str_starts_with($function, $actualClassName . '::') && $traitAliases === []) { - return self::$effectiveFunctionCache[$function][$actualClassName] = $function; + if ($traitAliases === [] && str_starts_with($function, $actualClassName . '::')) { + return self::$effectiveFunctionCache[$actualClassName][$function] = $function; } [$classOrTrait, $methodName] = explode('::', $function, 2); @@ -593,13 +592,13 @@ public static function resolveEffectiveFunction(string $function, object|string| $frameFunc = $frame['function']; $frameClass = $frame['class'] ?? ''; if (($frameClass === $actualClassName || $frameClass === $classOrTrait) && isset($traitAliases[$frameFunc])) { - return self::$effectiveFunctionCache[$function][$actualClassName] = $actualClassName . '::' . $frameFunc; + return self::$effectiveFunctionCache[$actualClassName][$function] = $actualClassName . '::' . $frameFunc; } } } } - return self::$effectiveFunctionCache[$function][$actualClassName] = $effectiveFunction; + return self::$effectiveFunctionCache[$actualClassName][$function] = $effectiveFunction; } /** diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 6e60719f..eeab718e 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -38,6 +38,26 @@ */ final class RuntimeTypeChecker { + public static bool $isEnabled = true; + + public static bool $paramsEnabled = true; + + public static bool $returnsEnabled = true; + + public static bool $paramsOutEnabled = true; + + public static bool $selfOutEnabled = true; + + /** + * @var array, sensitive: array, conditionals: ?array}> + */ + private static array $simpleScopePlanCache = []; + + /** + * @var array + */ + private static array $simpleReturnPlanCache = []; + private static ?TypeValidatorRegistry $registry = null; /** @@ -57,6 +77,8 @@ final class RuntimeTypeChecker */ public static function reset(): void { + self::$simpleScopePlanCache = []; + self::$simpleReturnPlanCache = []; self::$hasMethodTemplatesCache = []; self::$checkedStaticProperties = []; IgnoreManager::reset(); @@ -449,13 +471,44 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string */ public static function setupScope(string $function, array $vars, object|string|null $thisOrClass = null): ErrorMessage|ScopeCleaner|null { - if (! Config::isEnabled() || ! Config::isParamsEnabled()) { + if (! self::$isEnabled || ! self::$paramsEnabled) { return null; } $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + // Fast-path: simple non-templated scope plan + if (isset(self::$simpleScopePlanCache[$effectiveFunction])) { + $plan = self::$simpleScopePlanCache[$effectiveFunction]; + if ($vars !== []) { + $registry = self::$registry ??= new TypeValidatorRegistry(); + $err = ParamChecker::validateSimpleParams( + $plan['types'], + $vars, + $effectiveFunction, + $registry, + $plan['sensitive'], + $plan['conditionals'], + false + ); + + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return null; + } + + $handled = ViolationCollector::handle($err, 'parameter', null, function: $effectiveFunction); + if ($handled instanceof ErrorMessage) { + return $handled; + } + } + } + + return null; + } + + // Slow-path / initial execution & analysis if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return null; } @@ -494,6 +547,14 @@ public static function setupScope(string $function, array $vars, object|string|n && $contract['isSimple'] && ($thisObj !== null || $contract['classTemplates'] === []) ) { + if ($functionKind !== ParamChecker::KIND_CONSTRUCT && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { + self::$simpleScopePlanCache[$effectiveFunction] = [ + 'types' => $contract['constrainedTypes'] ?? $contract['types'], + 'sensitive' => $contract['sensitiveParams'], + 'conditionals' => $contract['paramConditionals'] ?? null, + ]; + } + if ($vars !== []) { $err = ParamChecker::validateSimpleParams( $contract['constrainedTypes'] ?? $contract['types'], @@ -675,13 +736,34 @@ public static function checkSelfOut(string $function, object $thisObj, ?array $v */ public static function checkReturn(string $function, mixed $value, object|string|null $thisOrClass = null, ?array $vars = []): mixed { - if (! Config::isEnabled() || ! Config::isReturnsEnabled()) { + if (! self::$isEnabled || ! self::$returnsEnabled) { return $value; } $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + if (isset(self::$simpleReturnPlanCache[$effectiveFunction])) { + $resolvedType = self::$simpleReturnPlanCache[$effectiveFunction]; + if ($resolvedType === false) { + return $value; + } + + $registry = self::$registry ??= new TypeValidatorRegistry(); + $err = $registry->validate($value, $resolvedType, 'Return value'); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + $formattedErr = ErrorFactory::createError($effectiveFunction . '(): ' . $err->getMessage()); + + return ViolationCollector::handle($formattedErr, 'return', $value, function: $effectiveFunction, target: 'return'); + } + + return $value; + } + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return $value; } @@ -695,6 +777,8 @@ public static function checkReturn(string $function, mixed $value, object|string $contract = DocblockParser::parse($effectiveFunction); if (! $isDynamicDispatch && ($contract['returnUnconstrained'] ?? false)) { + self::$simpleReturnPlanCache[$effectiveFunction] = false; + return $value; } @@ -716,10 +800,25 @@ public static function checkReturn(string $function, mixed $value, object|string if ($resolvedType instanceof IdentifierTypeNode) { $lowerName = strtolower($resolvedType->name); if ($lowerName === 'mixed' || $lowerName === 'array') { + self::$simpleReturnPlanCache[$effectiveFunction] = false; + return $value; } } + $isTraversableIterable = false; + if ($resolvedType instanceof IdentifierTypeNode) { + $baseName = strtolower(ltrim($resolvedType->name, '\\')); + $isTraversableIterable = isset(ReturnChecker::GENERIC_ITERABLES[$baseName]); + } elseif ($resolvedType instanceof GenericTypeNode) { + $baseName = strtolower(ltrim((string) $resolvedType->type, '\\')); + $isTraversableIterable = isset(ReturnChecker::GENERIC_ITERABLES[$baseName]); + } + + if (! $isTraversableIterable && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { + self::$simpleReturnPlanCache[$effectiveFunction] = $resolvedType; + } + $err = $registry->validate($value, $resolvedType, 'Return value'); if ($err !== null) { if (IgnoreManager::isCallerIgnored()) { @@ -731,17 +830,8 @@ public static function checkReturn(string $function, mixed $value, object|string return ViolationCollector::handle($formattedErr, 'return', $value, function: $effectiveFunction, target: 'return'); } - if ($value instanceof Traversable) { - $baseName = ''; - if ($resolvedType instanceof IdentifierTypeNode) { - $baseName = strtolower(ltrim($resolvedType->name, '\\')); - } elseif ($resolvedType instanceof GenericTypeNode) { - $baseName = strtolower(ltrim((string) $resolvedType->type, '\\')); - } - - if (isset(ReturnChecker::GENERIC_ITERABLES[$baseName])) { - return self::wrapIterable($effectiveFunction, 'return', $value); - } + if ($isTraversableIterable && $value instanceof Traversable) { + return self::wrapIterable($effectiveFunction, 'return', $value); } return $value; diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index c0463091..e6d59571 100644 --- a/src/Internal/Util/Config.php +++ b/src/Internal/Util/Config.php @@ -873,6 +873,12 @@ public static function reset(): void self::$processEnvEnabled = null; self::$hasProcessEnvOverride = false; + RuntimeTypeChecker::$isEnabled = true; + RuntimeTypeChecker::$paramsEnabled = true; + RuntimeTypeChecker::$returnsEnabled = true; + RuntimeTypeChecker::$paramsOutEnabled = true; + RuntimeTypeChecker::$selfOutEnabled = true; + DocblockParser::reset(); ParamChecker::reset(); ReturnChecker::reset(); @@ -947,6 +953,12 @@ private static function syncFlags(array $config): void self::$inlineScalars = (bool) ($inline['scalars'] ?? true); self::$inlineArrays = (bool) ($inline['arrays'] ?? true); self::$inlineObjects = (bool) ($inline['objects'] ?? true); + + RuntimeTypeChecker::$isEnabled = self::$enabled; + RuntimeTypeChecker::$paramsEnabled = self::$params; + RuntimeTypeChecker::$returnsEnabled = self::$returns; + RuntimeTypeChecker::$paramsOutEnabled = self::$params && self::$paramsOut; + RuntimeTypeChecker::$selfOutEnabled = self::$selfOut; } private static function probeProcessEnvOverrides(): void @@ -980,4 +992,4 @@ private static function resolveEnabledOverride(string $key, ?string $cachedProce return null; } -} +} \ No newline at end of file diff --git a/src/Internal/Validator/ArrayShapeValidator.php b/src/Internal/Validator/ArrayShapeValidator.php index 664a8bc2..0633d598 100644 --- a/src/Internal/Validator/ArrayShapeValidator.php +++ b/src/Internal/Validator/ArrayShapeValidator.php @@ -72,7 +72,7 @@ final class ArrayShapeValidator implements TypeValidatorInterface private const CHECK_STRING_MAP = 22; private const CHECK_INT_MAP = 23; - + private const CHECK_CLASS = 24; /** diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 39bda670..6810211f 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -22,12 +22,26 @@ use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; +use WeakMap; /** * @internal Validates values against generic AST structures (int ranges, class-string, list, array, object generics, key-of, value-of, int-mask, int-mask-of). */ final class GenericValidator implements TypeValidatorInterface { + private const KIND_FALLBACK = 0; + private const KIND_LIST = 1; + private const KIND_NON_EMPTY_LIST = 2; + private const KIND_ARRAY = 3; + private const KIND_NON_EMPTY_ARRAY = 4; + private const KIND_INT_RANGE = 5; + private const KIND_CLASS_STRING = 6; + private const KIND_KEY_OF = 7; + private const KIND_VALUE_OF = 8; + private const KIND_INT_MASK = 9; + private const KIND_INT_MASK_OF = 10; + private const KIND_OBJECT_GENERIC = 11; + private const BUILTIN_GENERICS = [ 'int' => true, 'integer' => true, @@ -47,6 +61,11 @@ final class GenericValidator implements TypeValidatorInterface 'int-mask-of' => true, ]; + /** + * @var WeakMap|null + */ + private static ?WeakMap $compiledGenericCache = null; + /** * @var array */ @@ -69,6 +88,7 @@ final class GenericValidator implements TypeValidatorInterface public static function reset(): void { + self::$compiledGenericCache = null; self::$constantCache = []; self::$enumKeyCache = []; self::$enumValueCache = []; @@ -82,23 +102,149 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali { /** @var GenericTypeNode $genericNode */ $genericNode = $node; - $typeName = $genericNode->type instanceof IdentifierTypeNode - ? $genericNode->type->name - : (string) $genericNode->type; + + if (self::$compiledGenericCache === null) { + self::$compiledGenericCache = new WeakMap(); + } + + $compiled = self::$compiledGenericCache[$genericNode] ?? null; + if ($compiled === null) { + self::$compiledGenericCache[$genericNode] = $compiled = $this->compileGeneric($genericNode); + } + + $kind = $compiled[0]; + + if ($kind === self::KIND_LIST) { + if (! \is_array($value) || ($value !== [] && ! array_is_list($value))) { + return ErrorFactory::createError($context . ' must be a list, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + $count = \count($value); + $valueTypeNode = $compiled[1]; + + if ($valueTypeNode === null || $count === 0) { + return null; + } + + return CollectionElementValidator::validateElements( + $value, + $valueTypeNode, + $context, + $registry, + isList: true, + isSensitive: $isSensitive, + count: $count, + ); + } + + if ($kind === self::KIND_NON_EMPTY_LIST) { + if (! \is_array($value) || ($value !== [] && ! array_is_list($value))) { + return ErrorFactory::createError($context . ' must be a list, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + $count = \count($value); + if ($count === 0) { + return ErrorFactory::createError($context . ' must be a non-empty list, empty array given'); + } + + $valueTypeNode = $compiled[1]; + if ($valueTypeNode === null) { + return null; + } + + return CollectionElementValidator::validateElements( + $value, + $valueTypeNode, + $context, + $registry, + isList: true, + isSensitive: $isSensitive, + count: $count, + ); + } + + if ($kind === self::KIND_ARRAY) { + return $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, false); + } + + if ($kind === self::KIND_NON_EMPTY_ARRAY) { + return $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, true); + } + + if ($kind === self::KIND_INT_RANGE) { + if (! \is_int($value)) { + return ErrorFactory::createError($context . ' must be of type int, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + [$minVal, $maxVal] = $compiled[1]; + $redact = $isSensitive || Config::isRedactValuesEnabled(); + + if ($minVal !== null && $value < $minVal) { + $valDisplay = $redact ? 'int given' : "$value given"; + + return ErrorFactory::createError($context . " must be >= $minVal, $valDisplay"); + } + + if ($maxVal !== null && $value > $maxVal) { + $valDisplay = $redact ? 'int given' : "$value given"; + + return ErrorFactory::createError($context . " must be <= $maxVal, $valDisplay"); + } + + return null; + } + + if ($kind === self::KIND_CLASS_STRING) { + return $this->validateClassString($value, $genericNode, $context, $isSensitive); + } + + if ($kind === self::KIND_KEY_OF) { + return $this->validateKeyOf($value, $genericNode, $context, $registry, $isSensitive); + } + + if ($kind === self::KIND_VALUE_OF) { + return $this->validateValueOf($value, $genericNode, $context, $registry, $isSensitive); + } + + if ($kind === self::KIND_INT_MASK) { + return $this->validateIntMask($value, $genericNode, $context, $isSensitive); + } + + if ($kind === self::KIND_INT_MASK_OF) { + return $this->validateIntMaskOf($value, $genericNode, $context, $isSensitive); + } + + return $this->validateObjectGeneric($value, $genericNode, $context, $isSensitive); + } + + /** + * @return array{0: int, 1: mixed} + */ + private function compileGeneric(GenericTypeNode $node): array + { + $typeName = $node->type instanceof IdentifierTypeNode + ? $node->type->name + : (string) $node->type; $baseType = strtolower($typeName); return match ($baseType) { - 'int', 'integer' => $this->validateIntRange($value, $genericNode, $context, $isSensitive), - 'class-string' => $this->validateClassString($value, $genericNode, $context, $isSensitive), - 'list' => $this->validateList($value, $genericNode, $context, $registry, $isSensitive, false), - 'non-empty-list', 'non-empty-array-list' => $this->validateList($value, $genericNode, $context, $registry, $isSensitive, true), - 'array', 'iterable', 'traversable', 'generator', 'iterator' => $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, false), - 'non-empty-array' => $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, true), - 'key-of' => $this->validateKeyOf($value, $genericNode, $context, $registry, $isSensitive), - 'value-of' => $this->validateValueOf($value, $genericNode, $context, $registry, $isSensitive), - 'int-mask' => $this->validateIntMask($value, $genericNode, $context, $isSensitive), - 'int-mask-of' => $this->validateIntMaskOf($value, $genericNode, $context, $isSensitive), - default => $this->validateObjectGeneric($value, $genericNode, $context, $isSensitive), + 'list' => [self::KIND_LIST, $node->genericTypes[0] ?? null], + 'non-empty-list', 'non-empty-array-list' => [self::KIND_NON_EMPTY_LIST, $node->genericTypes[0] ?? null], + 'array', 'iterable', 'traversable', 'generator', 'iterator' => [self::KIND_ARRAY, null], + 'non-empty-array' => [self::KIND_NON_EMPTY_ARRAY, null], + 'int', 'integer' => [ + self::KIND_INT_RANGE, + [ + isset($node->genericTypes[0]) ? $this->resolveIntBound($node->genericTypes[0]) : null, + isset($node->genericTypes[1]) ? $this->resolveIntBound($node->genericTypes[1]) : null, + ], + ], + 'class-string' => [self::KIND_CLASS_STRING, $node->genericTypes[0] ?? null], + 'key-of' => [self::KIND_KEY_OF, null], + 'value-of' => [self::KIND_VALUE_OF, null], + 'int-mask' => [self::KIND_INT_MASK, null], + 'int-mask-of' => [self::KIND_INT_MASK_OF, null], + default => [self::KIND_OBJECT_GENERIC, (string) $node->type], }; } @@ -501,34 +647,6 @@ private function resolveMaskOfPattern(string $className, string $pattern): array return self::$maskOfCache[$cacheKey] = [$allowedMask, $foundFlags]; } - private function validateList(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false, bool $requireNonEmpty = false): ?ErrorMessage - { - if (! \is_array($value) || ($value !== [] && ! array_is_list($value))) { - return ErrorFactory::createError($context . ' must be a list, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); - } - - $count = \count($value); - - if ($requireNonEmpty && $count === 0) { - return ErrorFactory::createError($context . ' must be a non-empty list, empty array given'); - } - - $valueTypeNode = $node->genericTypes[0] ?? null; - if ($valueTypeNode === null || $count === 0) { - return null; - } - - return CollectionElementValidator::validateElements( - $value, - $valueTypeNode, - $context, - $registry, - isList: true, - isSensitive: $isSensitive, - count: $count, - ); - } - private function validateArray(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false, bool $requireNonEmpty = false): ?ErrorMessage { if (! \is_array($value) && ! ($value instanceof \Traversable)) { @@ -713,35 +831,6 @@ private function resolveIntBound(PhpDocNode $node): ?int return null; } - private function validateIntRange(mixed $value, GenericTypeNode $node, string $context, bool $isSensitive = false): ?ErrorMessage - { - if (! \is_int($value)) { - return ErrorFactory::createError($context . ' must be of type int, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); - } - - $minNode = $node->genericTypes[0] ?? null; - $maxNode = $node->genericTypes[1] ?? null; - - $minVal = $minNode !== null ? $this->resolveIntBound($minNode) : null; - $maxVal = $maxNode !== null ? $this->resolveIntBound($maxNode) : null; - - $redact = $isSensitive || Config::isRedactValuesEnabled(); - - if ($minVal !== null && $value < $minVal) { - $valDisplay = $redact ? 'int given' : "$value given"; - - return ErrorFactory::createError($context . " must be >= $minVal, $valDisplay"); - } - - if ($maxVal !== null && $value > $maxVal) { - $valDisplay = $redact ? 'int given' : "$value given"; - - return ErrorFactory::createError($context . " must be <= $maxVal, $valDisplay"); - } - - return null; - } - private function validateClassString(mixed $value, GenericTypeNode $node, string $context, bool $isSensitive = false): ?ErrorMessage { if (! \is_string($value) || ! ClassNameValidator::isValidClassString($value)) { diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index 62eb13f9..3d88f0af 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -42,13 +42,6 @@ final class TypeValidatorRegistry private CallableValidator $callableValidator; - /** - * Static map for fast validator resolution. - * - * @var array - */ - private array $validatorMap; - public static function reset(): void { GenericValidator::reset(); @@ -67,19 +60,6 @@ public function __construct() $this->objectShapeValidator = new ObjectShapeValidator(); $this->constValidator = new ConstValidator(); $this->callableValidator = new CallableValidator(); - - $this->validatorMap = [ - IdentifierTypeNode::class => $this->identifierValidator, - GenericTypeNode::class => $this->genericValidator, - UnionTypeNode::class => $this->unionValidator, - NullableTypeNode::class => $this->nullableValidator, - ArrayTypeNode::class => $this->arrayValidator, - ArrayShapeNode::class => $this->arrayShapeValidator, - ObjectShapeNode::class => $this->objectShapeValidator, - IntersectionTypeNode::class => $this->intersectionValidator, - ConstTypeNode::class => $this->constValidator, - CallableTypeNode::class => $this->callableValidator, - ]; } /** @@ -89,16 +69,26 @@ public function validate(mixed $value, TypeNode $node, string $context = '', boo { if ($node instanceof IdentifierTypeNode) { $ok = match ($node->name) { - 'int' => \is_int($value), + 'int', 'integer' => \is_int($value), 'string' => \is_string($value), 'positive-int' => \is_int($value) && $value > 0, 'non-empty-string' => \is_string($value) && $value !== '', - 'bool' => \is_bool($value), - 'float' => \is_float($value) || \is_int($value), + 'bool', 'boolean' => \is_bool($value), + 'float', 'double' => \is_float($value) || \is_int($value), 'array-key' => \is_int($value) || \is_string($value), 'array' => \is_array($value), + 'list' => \is_array($value) && ($value === [] || array_is_list($value)), + 'non-empty-array' => \is_array($value) && \count($value) > 0, + 'non-empty-list' => \is_array($value) && \count($value) > 0 && array_is_list($value), + 'non-negative-int', 'unsigned-int' => \is_int($value) && $value >= 0, + 'negative-int' => \is_int($value) && $value < 0, + 'non-positive-int' => \is_int($value) && $value <= 0, + 'non-zero-int' => \is_int($value) && $value !== 0, 'mixed' => true, 'null' => $value === null, + 'true' => $value === true, + 'false' => $value === false, + 'scalar' => \is_scalar($value), default => false, }; @@ -109,11 +99,42 @@ public function validate(mixed $value, TypeNode $node, string $context = '', boo return $this->identifierValidator->validate($value, $node, $context, $this, $isSensitive); } - $validator = $this->validatorMap[$node::class] ?? null; - if ($validator === null) { - return null; + if ($node instanceof ArrayShapeNode) { + return $this->arrayShapeValidator->validate($value, $node, $context, $this, $isSensitive); + } + + if ($node instanceof GenericTypeNode) { + return $this->genericValidator->validate($value, $node, $context, $this, $isSensitive); + } + + if ($node instanceof UnionTypeNode) { + return $this->unionValidator->validate($value, $node, $context, $this, $isSensitive); + } + + if ($node instanceof NullableTypeNode) { + return $this->nullableValidator->validate($value, $node, $context, $this, $isSensitive); + } + + if ($node instanceof ArrayTypeNode) { + return $this->arrayValidator->validate($value, $node, $context, $this, $isSensitive); + } + + if ($node instanceof ConstTypeNode) { + return $this->constValidator->validate($value, $node, $context, $this, $isSensitive); + } + + if ($node instanceof ObjectShapeNode) { + return $this->objectShapeValidator->validate($value, $node, $context, $this, $isSensitive); + } + + if ($node instanceof IntersectionTypeNode) { + return $this->intersectionValidator->validate($value, $node, $context, $this, $isSensitive); + } + + if ($node instanceof CallableTypeNode) { + return $this->callableValidator->validate($value, $node, $context, $this, $isSensitive); } - return $validator->validate($value, $node, $context, $this, $isSensitive); + return null; } } From 8901e4469ea4bb69443796a3ebe0ebdf4f5ffffb Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 17 Nov 2026 17:33:38 +0800 Subject: [PATCH 04/25] Add /benchmark/ directory to .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 4f6aca70..83c4434e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ benchmark.php .php-cs-fixer.cache /app /coverage-report -/coverage \ No newline at end of file +/coverage +/benchmark/ From 055913e3932e1b0131663c3f9e6c3c2b8f35993c Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 17 Nov 2026 17:48:00 +0800 Subject: [PATCH 05/25] Enhance type evaluation by adding trusted variable types to evaluators and static type checks to elimanate return type checking --- .../Evaluator/ArrayLiteralEvaluator.php | 98 ++++---- .../Evaluator/GeneratorEvaluator.php | 7 +- .../Ast/Elimination/StaticTypeEvaluator.php | 39 ++-- src/Internal/Ast/FunctionContractInjector.php | 215 +++++++++++++++++- .../ParameterTypeTrackingEliminationTest.php | 160 +++++++++++++ 5 files changed, 446 insertions(+), 73 deletions(-) create mode 100644 tests/Internal/Ast/Elimination/ParameterTypeTrackingEliminationTest.php diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php index d41c07ee..4e9f1fa6 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -52,15 +52,14 @@ final class ArrayLiteralEvaluator /** * Determines whether an AST array expression satisfies a target type contract. * - * Flow of logic: - * 1. Empty arrays ([]) are checked against types that permit empty collections. - * 2. Bare array/iterable identifiers (array, iterable, list) are evaluated. - * 3. Sequential lists (list, non-empty-list, T[]) verify keys are 0..n-1 and all values satisfy T. - * 4. Typed key-value maps (array) verify all keys satisfy K and all values satisfy V. - * 5. Array shapes (array{id: int, ...}) verify required keys, unexpected keys, and field types. + * @param array $trustedVariableTypes */ - public static function satisfies(Array_ $arrayExpr, TypeNode $typeNode, string $currentFile = ''): bool - { + public static function satisfies( + Array_ $arrayExpr, + TypeNode $typeNode, + string $currentFile = '', + array $trustedVariableTypes = [] + ): bool { $count = \count($arrayExpr->items); if ($count === 0) { @@ -72,15 +71,15 @@ public static function satisfies(Array_ $arrayExpr, TypeNode $typeNode, string $ } if ($typeNode instanceof ArrayTypeNode) { - return self::satisfiesList($arrayExpr, $typeNode->type, false, $currentFile); + return self::satisfiesList($arrayExpr, $typeNode->type, false, $currentFile, $trustedVariableTypes); } if ($typeNode instanceof GenericTypeNode) { - return self::satisfiesGenericArray($arrayExpr, $typeNode, $currentFile); + return self::satisfiesGenericArray($arrayExpr, $typeNode, $currentFile, $trustedVariableTypes); } if ($typeNode instanceof ArrayShapeNode) { - return self::satisfiesArrayShape($arrayExpr, $typeNode, $currentFile); + return self::satisfiesArrayShape($arrayExpr, $typeNode, $currentFile, $trustedVariableTypes); } return false; @@ -88,8 +87,6 @@ public static function satisfies(Array_ $arrayExpr, TypeNode $typeNode, string $ /** * Checks if a type contract permits an empty array ([]). - * Returns true for unbounded array/list/iterable, T[], and shapes with only optional keys. - * Returns false for non-empty-array, non-empty-list, and shapes with required keys. */ public static function satisfiesEmptyArray(TypeNode $typeNode): bool { @@ -135,48 +132,54 @@ private static function satisfiesIdentifierArray(Array_ $arrayExpr, IdentifierTy } /** - * Evaluates an array expression against generic array containers: - * - Single template argument: list, non-empty-list, array - * - Double template argument: array, non-empty-array + * @param array $trustedVariableTypes */ - private static function satisfiesGenericArray(Array_ $arrayExpr, GenericTypeNode $node, string $currentFile): bool - { + private static function satisfiesGenericArray( + Array_ $arrayExpr, + GenericTypeNode $node, + string $currentFile, + array $trustedVariableTypes = [] + ): bool { $base = strtolower((string) $node->type); $genericCount = \count($node->genericTypes); if ($base === 'list' && $genericCount >= 1) { - return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile); + return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile, $trustedVariableTypes); } if ($base === 'non-empty-list' && $genericCount >= 1) { - return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile); + return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile, $trustedVariableTypes); } if (($base === 'array' || $base === 'iterable') && $genericCount === 1) { - return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile); + return self::satisfiesList($arrayExpr, $node->genericTypes[0], false, $currentFile, $trustedVariableTypes); } if (($base === 'array' || $base === 'iterable') && $genericCount >= 2) { - return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], false, $currentFile); + return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], false, $currentFile, $trustedVariableTypes); } if ($base === 'non-empty-array' && $genericCount === 1) { - return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile); + return self::satisfiesList($arrayExpr, $node->genericTypes[0], true, $currentFile, $trustedVariableTypes); } if ($base === 'non-empty-array' && $genericCount >= 2) { - return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], true, $currentFile); + return self::satisfiesKeyValueArray($arrayExpr, $node->genericTypes[0], $node->genericTypes[1], true, $currentFile, $trustedVariableTypes); } return false; } /** - * Verifies that all array items have sequential integer keys (0..n-1) - * and every item value statically satisfies the element contract T. + * @param array $trustedVariableTypes */ - private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, bool $requireNonEmpty, string $currentFile): bool - { + private static function satisfiesList( + Array_ $arrayExpr, + TypeNode $itemType, + bool $requireNonEmpty, + string $currentFile, + array $trustedVariableTypes = [] + ): bool { $count = \count($arrayExpr->items); if ($requireNonEmpty && $count === 0) { return false; @@ -195,7 +198,7 @@ private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, boo } $expectedIdx++; - if (! StaticTypeEvaluator::satisfies($item->value, $itemType, $currentFile)) { + if (! StaticTypeEvaluator::satisfies($item->value, $itemType, $currentFile, $trustedVariableTypes)) { return false; } } @@ -204,11 +207,16 @@ private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, boo } /** - * Verifies that every key in the array expression satisfies key contract K - * and every corresponding value satisfies value contract V. + * @param array $trustedVariableTypes */ - private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyType, TypeNode $valueType, bool $requireNonEmpty, string $currentFile): bool - { + private static function satisfiesKeyValueArray( + Array_ $arrayExpr, + TypeNode $keyType, + TypeNode $valueType, + bool $requireNonEmpty, + string $currentFile, + array $trustedVariableTypes = [] + ): bool { $count = \count($arrayExpr->items); if ($requireNonEmpty && $count === 0) { return false; @@ -232,11 +240,11 @@ private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyT return false; } - if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile)) { + if (! StaticTypeEvaluator::satisfies($keyExpr, $keyType, $currentFile, $trustedVariableTypes)) { return false; } - if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile)) { + if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile, $trustedVariableTypes)) { return false; } } @@ -245,12 +253,14 @@ private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyT } /** - * Evaluates an array expression against a sealed or unsealed ArrayShapeNode. - * Guarantees all required keys exist, no unsealed keys intrude in sealed shapes, - * and all value expressions satisfy their corresponding shape property contracts. + * @param array $trustedVariableTypes */ - private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $shapeNode, string $currentFile): bool - { + private static function satisfiesArrayShape( + Array_ $arrayExpr, + ArrayShapeNode $shapeNode, + string $currentFile, + array $trustedVariableTypes = [] + ): bool { if ($shapeNode->kind === ArrayShapeNode::KIND_LIST && ! self::isSequentialList($arrayExpr)) { return false; } @@ -304,7 +314,7 @@ private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $s continue; } - if (! StaticTypeEvaluator::satisfies($actualItems[$expectedKey], $shapeItem->valueType, $currentFile)) { + if (! StaticTypeEvaluator::satisfies($actualItems[$expectedKey], $shapeItem->valueType, $currentFile, $trustedVariableTypes)) { return false; } } @@ -321,12 +331,12 @@ private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $s if ($shapeNode->unsealedType !== null) { if ($shapeNode->unsealedType->keyType !== null) { $keyExpr = \is_int($actualKey) ? new LNumber($actualKey) : new String_($actualKey); - if (! StaticTypeEvaluator::satisfies($keyExpr, $shapeNode->unsealedType->keyType, $currentFile)) { + if (! StaticTypeEvaluator::satisfies($keyExpr, $shapeNode->unsealedType->keyType, $currentFile, $trustedVariableTypes)) { return false; } } - if (! StaticTypeEvaluator::satisfies($actualValueExpr, $shapeNode->unsealedType->valueType, $currentFile)) { + if (! StaticTypeEvaluator::satisfies($actualValueExpr, $shapeNode->unsealedType->valueType, $currentFile, $trustedVariableTypes)) { return false; } } @@ -370,4 +380,4 @@ private static function hasConcreteItem(Array_ $arrayExpr): bool return false; } -} +} \ No newline at end of file diff --git a/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php index 82edffa8..097e0bc9 100644 --- a/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/GeneratorEvaluator.php @@ -197,11 +197,14 @@ public static function canEliminateYieldFrom( /** * Determines whether `RuntimeTypeChecker::checkGeneratorReturn()` can be statically eliminated. + * + * @param array $trustedVariableTypes */ public static function canEliminateGeneratorReturn( ?Expr $returnExpr, ?TypeNode $returnType, - string $currentFile = '' + string $currentFile = '', + array $trustedVariableTypes = [] ): bool { if (! Config::isEliminateStaticallyProvenChecksEnabled()) { return false; @@ -213,7 +216,7 @@ public static function canEliminateGeneratorReturn( $effectiveExpr = $returnExpr ?? new ConstFetch(new Name('null')); - return StaticTypeEvaluator::satisfies($effectiveExpr, $returnType, $currentFile); + return StaticTypeEvaluator::satisfies($effectiveExpr, $returnType, $currentFile, $trustedVariableTypes); } /** diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index ddd22382..ad3f01dc 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -7,6 +7,7 @@ use PhpParser\Node\Expr; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\Ternary; +use PhpParser\Node\Expr\Variable; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; @@ -16,6 +17,7 @@ use TypePHP\Internal\Ast\Elimination\Evaluator\ConstantAndEnumEvaluator; use TypePHP\Internal\Ast\Elimination\Evaluator\ObjectEvaluator; use TypePHP\Internal\Ast\Elimination\Evaluator\ScalarEvaluator; +use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Util\Config; /** @@ -46,17 +48,14 @@ final class StaticTypeEvaluator /** * Determines whether an AST expression deterministically satisfies a TypeNode contract. * - * Flow of logic: - * 1. Returns false if `eliminate_statically_proven_checks` is disabled in configuration. - * 2. Rejects IntersectionTypeNode unconditionally (deferred to runtime to avoid autoloader deadlocks). - * 3. Rejects generic object templates to ensure runtime WeakMap registrations occur. - * 4. Evaluates Ternary expressions: if both `if` and `else` branches satisfy the contract, - * the expression is satisfied regardless of runtime condition. - * 5. Handles NullableTypeNode and UnionTypeNode disjunctions. - * 6. Delegates array expressions, constants/enums, object instantiations, and arithmetic/scalars. + * @param array $trustedVariableTypes */ - public static function satisfies(Expr $expr, TypeNode $typeNode, string $currentFile = ''): bool - { + public static function satisfies( + Expr $expr, + TypeNode $typeNode, + string $currentFile = '', + array $trustedVariableTypes = [] + ): bool { if (! Config::isEliminateStaticallyProvenChecksEnabled()) { return false; } @@ -72,9 +71,17 @@ public static function satisfies(Expr $expr, TypeNode $typeNode, string $current } } + if ($expr instanceof Variable && \is_string($expr->name) && isset($trustedVariableTypes[$expr->name])) { + return TemplateManager::checkVariance( + $trustedVariableTypes[$expr->name], + $typeNode, + GenericTypeNode::VARIANCE_COVARIANT + ); + } + if ($expr instanceof Ternary && $expr->if !== null) { - return self::satisfies($expr->if, $typeNode, $currentFile) - && self::satisfies($expr->else, $typeNode, $currentFile); + return self::satisfies($expr->if, $typeNode, $currentFile, $trustedVariableTypes) + && self::satisfies($expr->else, $typeNode, $currentFile, $trustedVariableTypes); } if ($typeNode instanceof NullableTypeNode) { @@ -82,12 +89,12 @@ public static function satisfies(Expr $expr, TypeNode $typeNode, string $current return true; } - return self::satisfies($expr, $typeNode->type, $currentFile); + return self::satisfies($expr, $typeNode->type, $currentFile, $trustedVariableTypes); } if ($typeNode instanceof UnionTypeNode) { foreach ($typeNode->types as $member) { - if (self::satisfies($expr, $member, $currentFile)) { + if (self::satisfies($expr, $member, $currentFile, $trustedVariableTypes)) { return true; } } @@ -96,11 +103,11 @@ public static function satisfies(Expr $expr, TypeNode $typeNode, string $current } if ($expr instanceof Array_) { - return ArrayLiteralEvaluator::satisfies($expr, $typeNode, $currentFile); + return ArrayLiteralEvaluator::satisfies($expr, $typeNode, $currentFile, $trustedVariableTypes); } return ConstantAndEnumEvaluator::satisfies($expr, $typeNode, $currentFile) || ObjectEvaluator::satisfies($expr, $typeNode, $currentFile) || ScalarEvaluator::satisfies($expr, $typeNode); } -} +} \ No newline at end of file diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index a970d0f9..e43997a9 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -8,11 +8,15 @@ use PhpParser\Node; use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; +use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use TypePHP\Internal\Ast\Elimination\EliminationSafetyPolicy; use TypePHP\Internal\Ast\Elimination\Evaluator\GeneratorEvaluator; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Docblock\DocblockExtractor; +use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\StubManager; /** @@ -141,6 +145,7 @@ public static function inject( $returnTypeNode = null; $hasMethodTemplates = false; + $declaredTemplates = []; if ($doc !== null) { try { $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); @@ -148,11 +153,14 @@ public static function inject( if ($returnTag !== null) { $returnTypeNode = $returnTag->type; } - $hasMethodTemplates = DocblockExtractor::extractTemplates($phpDocNode) !== []; + $declaredTemplates = DocblockExtractor::extractTemplates($phpDocNode); + $hasMethodTemplates = $declaredTemplates !== []; } catch (\Throwable) { } } + $trustedParamTypes = self::collectTrustedParamTypes($node, $doc, $declaredTemplates, $currentFile); + if ($hasReturn || $hasParamOut || $hasSelfOut) { $node->stmts = self::isGenerator($node) ? self::wrapGeneratorReturns( @@ -166,7 +174,8 @@ public static function inject( $needsReturnVars, $hasParamOut ? $byRefParams : [], $hasSelfOut, - $hasParam + $hasParam, + $trustedParamTypes ) : self::wrapNonGeneratorReturns( $node->stmts, @@ -180,13 +189,186 @@ public static function inject( $node, $classContext, $returnTypeNode, - $currentFile + $currentFile, + $trustedParamTypes ); } $node->stmts = [...$injectedStmts, ...$node->stmts]; } + /** + * Extracts concrete parameter contracts and verifies they are never mutated in the body. + * + * @param array $declaredTemplates + * + * @return array + */ + private static function collectTrustedParamTypes( + Node\Stmt\Function_|Node\Stmt\ClassMethod $node, + ?Doc $doc, + array $declaredTemplates, + string $currentFile + ): array { + if ($node->stmts === null || $node->stmts === [] || $node->params === []) { + return []; + } + + $candidateNames = []; + foreach ($node->params as $p) { + if (! $p->byRef && $p->var instanceof Node\Expr\Variable && \is_string($p->var->name)) { + $candidateNames[$p->var->name] = true; + } + } + + if ($candidateNames === []) { + return []; + } + + $unmutatedNames = self::findUnmutatedVariables($node->stmts, $candidateNames); + if ($unmutatedNames === []) { + return []; + } + + $paramTags = []; + if ($doc !== null) { + try { + $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); + $paramTags = DocblockExtractor::getParamTags($phpDocNode); + } catch (\Throwable) { + } + } + + $trustedTypes = []; + foreach ($node->params as $p) { + if (! ($p->var instanceof Node\Expr\Variable) || ! \is_string($p->var->name)) { + continue; + } + + $pName = $p->var->name; + if (! isset($unmutatedNames[$pName])) { + continue; + } + + $typeNode = null; + if (isset($paramTags[$pName])) { + $typeNode = $paramTags[$pName]->type; + } elseif ($p->type !== null) { + if ($p->type instanceof Node\Identifier) { + $typeNode = new IdentifierTypeNode($p->type->name); + } elseif ($p->type instanceof Node\NullableType && $p->type->type instanceof Node\Identifier) { + $typeNode = new NullableTypeNode(new IdentifierTypeNode($p->type->type->name)); + } + } + + if ($typeNode === null) { + continue; + } + + if ($currentFile !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile); + } + + if ($declaredTemplates !== [] && DocblockParser::typeReferencesTemplate($typeNode, $declaredTemplates)) { + continue; + } + + if ($typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'mixed') { + continue; + } + + $trustedTypes[$pName] = $typeNode; + } + + return $trustedTypes; + } + + /** + * Traverses statements to identify parameters that are never mutated or passed by reference. + * + * @param array $stmts + * @param array $candidateNames + * + * @return array + */ + private static function findUnmutatedVariables(array $stmts, array $candidateNames): array + { + $unmutated = $candidateNames; + + $visitor = new class ($unmutated) extends NodeVisitorAbstract { + /** + * @param array $unmutated + */ + public function __construct(public array &$unmutated) + { + } + + public function enterNode(Node $node): ?int + { + if ($this->unmutated === []) { + return NodeTraverser::STOP_TRAVERSAL; + } + + if ($node instanceof Node\Expr\Assign || $node instanceof Node\Expr\AssignOp) { + $this->disqualifyTarget($node->var); + } elseif ($node instanceof Node\Expr\AssignRef) { + $this->disqualifyTarget($node->var); + $this->disqualifyTarget($node->expr); + } elseif ( + $node instanceof Node\Expr\PreInc + || $node instanceof Node\Expr\PostInc + || $node instanceof Node\Expr\PreDec + || $node instanceof Node\Expr\PostDec + ) { + $this->disqualifyTarget($node->var); + } elseif ($node instanceof Node\Stmt\Unset_) { + foreach ($node->vars as $v) { + $this->disqualifyTarget($v); + } + } elseif ($node instanceof Node\ArrayItem && $node->byRef) { + $this->disqualifyTarget($node->value); + } elseif ($node instanceof Node\Expr\Closure) { + foreach ($node->uses as $u) { + if ($u->byRef && $u->var instanceof Node\Expr\Variable && \is_string($u->var->name)) { + unset($this->unmutated[$u->var->name]); + } + } + } elseif ($node instanceof Node\Expr\CallLike) { + foreach ($node->getArgs() as $arg) { + if ($arg->value instanceof Node\Expr\Variable && \is_string($arg->value->name)) { + unset($this->unmutated[$arg->value->name]); + } + } + } + + return null; + } + + private function disqualifyTarget(Node $target): void + { + while ($target instanceof Node\Expr\ArrayDimFetch || $target instanceof Node\Expr\PropertyFetch) { + $target = $target->var; + } + + if ($target instanceof Node\Expr\Variable && \is_string($target->name)) { + unset($this->unmutated[$target->name]); + } elseif ($target instanceof Node\Expr\Array_ || $target instanceof Node\Expr\List_) { + foreach ($target->items as $item) { + if ($item !== null) { + $this->disqualifyTarget($item->value); + } + } + } + } + }; + + $traverser = new NodeTraverser(); + $traverser->addVisitor($visitor); + $traverser->traverse($stmts); + + return $visitor->unmutated; + } + public static function buildSelfOutCheckStmt(Node\Expr $thisArg, bool $needsReturnVars = false): Node\Stmt\Expression { $varsArg = $needsReturnVars @@ -895,6 +1077,7 @@ public static function buildWrappedYieldNode( * @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 * * @return array */ @@ -909,7 +1092,8 @@ private static function wrapGeneratorReturns( bool $needsReturnVars = false, array $byRefParams = [], bool $hasSelfOut = false, - bool $hasScope = false + bool $hasScope = false, + array $trustedParamTypes = [] ): array { $canEliminate = $functionNode !== null && ! $hasMethodTemplates @@ -932,10 +1116,12 @@ private static function wrapGeneratorReturns( $needsReturnVars, $byRefParams, $hasSelfOut, + $trustedParamTypes ) extends NodeVisitorAbstract { /** * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract * @param array $byRefParams + * @param array $trustedParamTypes */ public function __construct( private Node\Expr $thisArg, @@ -944,6 +1130,7 @@ public function __construct( private bool $needsReturnVars, private array $byRefParams, private bool $hasSelfOut, + private array $trustedParamTypes ) { } @@ -1076,7 +1263,8 @@ public function enterNode(Node $n): int|Node|array|null && GeneratorEvaluator::canEliminateGeneratorReturn( $candidateExpr, $this->genContract['return'], - $this->currentFile + $this->currentFile, + $this->trustedParamTypes ) ) { return $exitStmts !== [] ? [...$exitStmts, $n] : $n; @@ -1130,7 +1318,7 @@ public function enterNode(Node $n): int|Node|array|null if ( $genContract === null - || ! GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile) + || ! GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile, $trustedParamTypes) ) { $scopeArg = new Node\Expr\BinaryOp\Coalesce( new Node\Expr\Variable('__typephpScope'), @@ -1164,6 +1352,7 @@ public function enterNode(Node $n): int|Node|array|null * @param array $stmts * @param array $byRefParams * @param array{name?: ?string, hasInheritance?: bool, hasRealInheritance?: bool, hasPropertyWithDoc?: bool, isReadonly?: bool, isFinal?: bool, hasTemplates?: bool}|null $classContext + * @param array $trustedParamTypes * * @return array */ @@ -1179,7 +1368,8 @@ private static function wrapNonGeneratorReturns( Node\Stmt\Function_|Node\Stmt\ClassMethod|null $functionNode = null, ?array $classContext = null, ?TypeNode $returnTypeNode = null, - string $currentFile = '' + string $currentFile = '', + array $trustedParamTypes = [] ): array { self::tagPrecedingAssignments($stmts); @@ -1195,11 +1385,13 @@ private static function wrapNonGeneratorReturns( $functionNode, $classContext, $returnTypeNode, - $currentFile + $currentFile, + $trustedParamTypes ) 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 */ public function __construct( private Node\Expr $thisArg, @@ -1212,7 +1404,8 @@ public function __construct( private Node\Stmt\Function_|Node\Stmt\ClassMethod|null $functionNode, private ?array $classContext, private ?TypeNode $returnTypeNode, - private string $currentFile + private string $currentFile, + private array $trustedParamTypes ) { } @@ -1274,7 +1467,7 @@ public function enterNode(Node $n): int|array|null && $this->functionNode !== null && $this->returnTypeNode !== null && EliminationSafetyPolicy::isReturnEliminationSafe($this->functionNode, $this->classContext, $this->returnTypeNode) - && StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile) + && StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile, $this->trustedParamTypes) ) { return $exitStmts !== [] ? [...$exitStmts, $n] : null; } @@ -1388,4 +1581,4 @@ public static function tagPrecedingAssignments(array $stmts): void } } } -} +} \ No newline at end of file diff --git a/tests/Internal/Ast/Elimination/ParameterTypeTrackingEliminationTest.php b/tests/Internal/Ast/Elimination/ParameterTypeTrackingEliminationTest.php new file mode 100644 index 00000000..f171a057 --- /dev/null +++ b/tests/Internal/Ast/Elimination/ParameterTypeTrackingEliminationTest.php @@ -0,0 +1,160 @@ + $itemIds + * + * @return array{order_id: positive-int, status: 'completed'} + */ + public function processOrder(int $orderId, string $customerName, array $meta, array $itemIds): array + { + return [ + 'order_id' => $orderId, + 'status' => 'completed', + ]; + } +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_order_service.php'); + + expect($transformed)->toContain('RuntimeTypeChecker::setupScope') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain("'order_id' => \$orderId") + ->and($transformed)->toContain("'status' => 'completed'") + ; + }); + + test('eliminates checkReturn when returning an unmutated parameter directly to a compatible return type', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::setupScope') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain('return $id;') + ; + }); + + test('retains checkReturn when parameter is reassigned inside the function body', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('retains checkReturn when parameter is decremented inside the function body', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('retains checkReturn when parameter is passed as an argument to a function call', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('retains checkReturn when parameter type does not satisfy the return contract (contravariant/wider)', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); + + test('retains checkReturn when parameter was declared by reference in method signature', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); +}); From f2259db0cd5c39cfc3cdd268c1dc0c8a98e9ffa2 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 17 Nov 2026 18:08:23 +0800 Subject: [PATCH 06/25] Add fast-path handling for common scalar identifiers in ParamChecker to improve performance --- src/Internal/Checker/ParamChecker.php | 31 +++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index f9e04450..ddedf682 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -372,6 +372,37 @@ public static function validateSimpleParams( } } + // Inline fast-path for common scalar identifiers to bypass TypeValidatorRegistry dispatch and Improve performance + if ($typeNode instanceof IdentifierTypeNode) { + $ok = match ($typeNode->name) { + 'int', 'integer' => \is_int($val), + 'string' => \is_string($val), + 'positive-int' => \is_int($val) && $val > 0, + 'non-empty-string' => \is_string($val) && $val !== '', + 'bool', 'boolean' => \is_bool($val), + 'float', 'double' => \is_float($val) || \is_int($val), + 'array-key' => \is_int($val) || \is_string($val), + 'array' => \is_array($val), + 'list' => \is_array($val) && ($val === [] || array_is_list($val)), + 'non-empty-array' => \is_array($val) && \count($val) > 0, + 'non-empty-list' => \is_array($val) && \count($val) > 0 && array_is_list($val), + 'non-negative-int', 'unsigned-int' => \is_int($val) && $val >= 0, + 'negative-int' => \is_int($val) && $val < 0, + 'non-positive-int' => \is_int($val) && $val <= 0, + 'non-zero-int' => \is_int($val) && $val !== 0, + 'mixed' => true, + 'null' => $val === null, + 'true' => $val === true, + 'false' => $val === false, + 'scalar' => \is_scalar($val), + default => false, + }; + + if ($ok) { + continue; + } + } + $isSensitive = $hasSensitive && ($sensitiveParams[$paramName] ?? false); $err = $registry->validate($val, $typeNode, '', $isSensitive); if ($err !== null) { From 61eb228e2c20a61b67600a85ceb306b80443bf11 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Tue, 17 Nov 2026 18:33:56 +0800 Subject: [PATCH 07/25] Enhance RuntimeTypeChecker with additional parameter check constants and optimize validation logic --- src/Internal/RuntimeTypeChecker.php | 240 +++++++++++++++++++++++----- 1 file changed, 197 insertions(+), 43 deletions(-) diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index eeab718e..769e8abe 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -38,6 +38,44 @@ */ final class RuntimeTypeChecker { + private const PARAM_CHECK_FALLBACK = 0; + + private const PARAM_CHECK_INT = 1; + + private const PARAM_CHECK_STRING = 2; + + private const PARAM_CHECK_POSITIVE_INT = 3; + + private const PARAM_CHECK_NON_EMPTY_STRING = 4; + + private const PARAM_CHECK_BOOL = 5; + + private const PARAM_CHECK_FLOAT = 6; + + private const PARAM_CHECK_ARRAY_KEY = 7; + + private const PARAM_CHECK_ARRAY = 8; + + private const PARAM_CHECK_LIST = 9; + + private const PARAM_CHECK_NON_NEGATIVE_INT = 10; + + private const PARAM_CHECK_NEGATIVE_INT = 11; + + private const PARAM_CHECK_NON_POSITIVE_INT = 12; + + private const PARAM_CHECK_NON_ZERO_INT = 13; + + private const PARAM_CHECK_MIXED = 14; + + private const PARAM_CHECK_NULL = 15; + + private const PARAM_CHECK_TRUE = 16; + + private const PARAM_CHECK_FALSE = 17; + + private const PARAM_CHECK_SCALAR = 18; + public static bool $isEnabled = true; public static bool $paramsEnabled = true; @@ -48,8 +86,10 @@ final class RuntimeTypeChecker public static bool $selfOutEnabled = true; + private static ?TypeValidatorRegistry $registry = null; + /** - * @var array, sensitive: array, conditionals: ?array}> + * @var array}> */ private static array $simpleScopePlanCache = []; @@ -58,8 +98,6 @@ final class RuntimeTypeChecker */ private static array $simpleReturnPlanCache = []; - private static ?TypeValidatorRegistry $registry = null; - /** * @var array */ @@ -107,7 +145,7 @@ public static function checkConstant( string $file = '', ?int $line = null ): mixed { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return $value; } @@ -154,7 +192,7 @@ public static function checkConstantClosureParam( string $file = '', ?int $line = null ): mixed { - if (! Config::isEnabled() || ! Config::isParamsEnabled()) { + if (! self::$isEnabled || ! self::$paramsEnabled) { return $value; } @@ -196,7 +234,7 @@ public static function checkConstantClosureReturn( string $file = '', ?int $line = null ): mixed { - if (! Config::isEnabled() || ! Config::isReturnsEnabled()) { + if (! self::$isEnabled || ! self::$returnsEnabled) { return $value; } @@ -246,7 +284,7 @@ public static function checkPropertyMemberAssign( return $value; } - if (! Config::isEnabled() || ! Config::isInlinePropertiesEnabled()) { + if (! self::$isEnabled || ! Config::isInlinePropertiesEnabled()) { return $value; } @@ -286,7 +324,7 @@ public static function checkMemberAssign( ?string $caller = null, mixed $thisOrClass = null ): mixed { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return $value; } @@ -320,7 +358,7 @@ public static function checkMemberAssign( */ public static function withPendingGeneric(string $typeString, \Closure $factory, string $file = '', mixed ...$args): mixed { - if (! Config::isEnabled() || ! Config::isInlineGenericsEnabled()) { + if (! self::$isEnabled || ! Config::isInlineGenericsEnabled()) { return $factory(...$args); } @@ -343,7 +381,7 @@ public static function checkStaticProperty( string $file = '', ?int $line = null ): mixed { - if (! Config::isEnabled() || ! Config::isInlinePropertiesEnabled()) { + if (! self::$isEnabled || ! Config::isInlinePropertiesEnabled()) { return $value; } @@ -372,7 +410,7 @@ public static function checkStaticProperty( */ public static function bindInstanceFromNode(object $instance, GenericTypeNode $typeNode, string $context = '', bool $forceBind = false): ?ErrorMessage { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return null; } @@ -412,7 +450,7 @@ public static function checkVariable( ?string $caller = null, mixed $thisOrClass = null ): mixed { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return $value; } @@ -447,7 +485,7 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string return $value; } - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return $value; } @@ -475,30 +513,63 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } - $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + $plan = self::$simpleScopePlanCache[$function] ?? null; - // Fast-path: simple non-templated scope plan - if (isset(self::$simpleScopePlanCache[$effectiveFunction])) { - $plan = self::$simpleScopePlanCache[$effectiveFunction]; - if ($vars !== []) { - $registry = self::$registry ??= new TypeValidatorRegistry(); - $err = ParamChecker::validateSimpleParams( - $plan['types'], - $vars, - $effectiveFunction, - $registry, - $plan['sensitive'], - $plan['conditionals'], - false - ); + // Fast-path: pre-compiled simple non-templated scope plan with direct class match + if ($plan !== null && ($thisOrClass === null || (\is_object($thisOrClass) ? $thisOrClass::class === $plan['class'] : $thisOrClass === $plan['class']))) { + if ($vars === []) { + return null; + } + + $registry = self::$registry ??= new TypeValidatorRegistry(); + $effectiveFunc = $plan['function']; + + foreach ($plan['items'] as $item) { + $paramName = $item[0]; + + if (isset($vars[$paramName])) { + $val = $vars[$paramName]; + } elseif (\array_key_exists($paramName, $vars)) { + $val = null; + } else { + continue; + } + $ok = match ($item[1]) { + self::PARAM_CHECK_POSITIVE_INT => \is_int($val) && $val > 0, + self::PARAM_CHECK_NON_EMPTY_STRING => \is_string($val) && $val !== '', + self::PARAM_CHECK_INT => \is_int($val), + 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_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)), + self::PARAM_CHECK_NON_NEGATIVE_INT => \is_int($val) && $val >= 0, + self::PARAM_CHECK_NEGATIVE_INT => \is_int($val) && $val < 0, + self::PARAM_CHECK_NON_POSITIVE_INT => \is_int($val) && $val <= 0, + self::PARAM_CHECK_NON_ZERO_INT => \is_int($val) && $val !== 0, + self::PARAM_CHECK_MIXED => true, + self::PARAM_CHECK_NULL => $val === null, + self::PARAM_CHECK_TRUE => $val === true, + self::PARAM_CHECK_FALSE => $val === false, + self::PARAM_CHECK_SCALAR => \is_scalar($val), + default => false, + }; + + if ($ok) { + continue; + } + + $err = $registry->validate($val, $item[2], '', $item[3]); if ($err !== null) { + $formattedErr = ErrorFactory::createError($effectiveFunc . '(): Argument $' . $paramName . $err->getMessage()); + if (IgnoreManager::isCallerIgnored()) { return null; } - $handled = ViolationCollector::handle($err, 'parameter', null, function: $effectiveFunction); + $handled = ViolationCollector::handle($formattedErr, 'parameter', null, function: $effectiveFunc); if ($handled instanceof ErrorMessage) { return $handled; } @@ -509,6 +580,9 @@ public static function setupScope(string $function, array $vars, object|string|n } // Slow-path / initial execution & analysis + $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; + $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return null; } @@ -547,12 +621,23 @@ public static function setupScope(string $function, array $vars, object|string|n && $contract['isSimple'] && ($thisObj !== null || $contract['classTemplates'] === []) ) { - if ($functionKind !== ParamChecker::KIND_CONSTRUCT && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { - self::$simpleScopePlanCache[$effectiveFunction] = [ - 'types' => $contract['constrainedTypes'] ?? $contract['types'], - 'sensitive' => $contract['sensitiveParams'], - 'conditionals' => $contract['paramConditionals'] ?? null, + $hasNoConditionals = ($contract['paramConditionals'] ?? null) === null || $contract['paramConditionals'] === []; + + if ($hasNoConditionals && $functionKind !== ParamChecker::KIND_CONSTRUCT && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { + $typesToValidate = $contract['constrainedTypes'] ?? $contract['types']; + $compiledItems = self::compileSimpleScopePlanItems($typesToValidate, $contract['sensitiveParams']); + $declaringClass = str_contains($effectiveFunction, '::') ? explode('::', $effectiveFunction, 2)[0] : null; + + $compiledPlan = [ + 'class' => $declaringClass, + 'function' => $effectiveFunction, + 'items' => $compiledItems, ]; + + self::$simpleScopePlanCache[$function] = $compiledPlan; + if ($function !== $effectiveFunction) { + self::$simpleScopePlanCache[$effectiveFunction] = $compiledPlan; + } } if ($vars !== []) { @@ -624,6 +709,49 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } + /** + * @param array $types + * @param array $sensitiveParams + * + * @return list + */ + private static function compileSimpleScopePlanItems(array $types, array $sensitiveParams): array + { + $items = []; + foreach ($types as $paramName => $typeNode) { + $isSensitive = $sensitiveParams[$paramName] ?? false; + $checkKind = self::PARAM_CHECK_FALLBACK; + + if ($typeNode instanceof IdentifierTypeNode) { + $checkKind = match (strtolower($typeNode->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, + 'array-key' => self::PARAM_CHECK_ARRAY_KEY, + 'array' => self::PARAM_CHECK_ARRAY, + 'list' => self::PARAM_CHECK_LIST, + 'non-negative-int', 'unsigned-int' => self::PARAM_CHECK_NON_NEGATIVE_INT, + 'negative-int' => self::PARAM_CHECK_NEGATIVE_INT, + 'non-positive-int' => self::PARAM_CHECK_NON_POSITIVE_INT, + 'non-zero-int' => self::PARAM_CHECK_NON_ZERO_INT, + 'mixed' => self::PARAM_CHECK_MIXED, + 'null' => self::PARAM_CHECK_NULL, + 'true' => self::PARAM_CHECK_TRUE, + 'false' => self::PARAM_CHECK_FALSE, + 'scalar' => self::PARAM_CHECK_SCALAR, + default => self::PARAM_CHECK_FALLBACK, + }; + } + + $items[] = [$paramName, $checkKind, $typeNode, $isSensitive]; + } + + return $items; + } + /** * Validates all incoming parameters against the function or method's declared contract. * @@ -631,7 +759,7 @@ public static function setupScope(string $function, array $vars, object|string|n */ public static function checkParams(string $function, array $vars, object|string|null $thisOrClass = null): ?ErrorMessage { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return null; } @@ -670,7 +798,7 @@ public static function checkParamOut( object|string|null $thisOrClass = null, ?array $vars = [] ): ?ErrorMessage { - if (! Config::isEnabled() || ! Config::isParamsOutEnabled()) { + if (! self::$isEnabled || ! self::$paramsOutEnabled) { return null; } @@ -706,7 +834,7 @@ public static function checkParamOut( */ public static function checkSelfOut(string $function, object $thisObj, ?array $vars = []): void { - if (! Config::isEnabled() || ! Config::isSelfOutEnabled()) { + if (! self::$isEnabled || ! self::$selfOutEnabled) { return; } @@ -740,6 +868,28 @@ public static function checkReturn(string $function, mixed $value, object|string return $value; } + // Fast-path: pre-compiled simple return plan + if (isset(self::$simpleReturnPlanCache[$function])) { + $resolvedType = self::$simpleReturnPlanCache[$function]; + if ($resolvedType === false) { + return $value; + } + + $registry = self::$registry ??= new TypeValidatorRegistry(); + $err = $registry->validate($value, $resolvedType, 'Return value'); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + $formattedErr = ErrorFactory::createError($function . '(): ' . $err->getMessage()); + + return ViolationCollector::handle($formattedErr, 'return', $value, function: $function, target: 'return'); + } + + return $value; + } + $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); @@ -764,6 +914,7 @@ public static function checkReturn(string $function, mixed $value, object|string return $value; } + // Slow-path / initial execution & analysis if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return $value; } @@ -777,6 +928,7 @@ public static function checkReturn(string $function, mixed $value, object|string $contract = DocblockParser::parse($effectiveFunction); if (! $isDynamicDispatch && ($contract['returnUnconstrained'] ?? false)) { + self::$simpleReturnPlanCache[$function] = false; self::$simpleReturnPlanCache[$effectiveFunction] = false; return $value; @@ -800,6 +952,7 @@ public static function checkReturn(string $function, mixed $value, object|string if ($resolvedType instanceof IdentifierTypeNode) { $lowerName = strtolower($resolvedType->name); if ($lowerName === 'mixed' || $lowerName === 'array') { + self::$simpleReturnPlanCache[$function] = false; self::$simpleReturnPlanCache[$effectiveFunction] = false; return $value; @@ -816,6 +969,7 @@ public static function checkReturn(string $function, mixed $value, object|string } if (! $isTraversableIterable && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { + self::$simpleReturnPlanCache[$function] = $resolvedType; self::$simpleReturnPlanCache[$effectiveFunction] = $resolvedType; } @@ -870,7 +1024,7 @@ public static function checkSend( object|string|null $thisOrClass = null, ?ScopeCleaner $scopeCleaner = null ): mixed { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return $sendValue; } @@ -903,7 +1057,7 @@ public static function checkGeneratorReturn( object|string|null $thisOrClass = null, ?ScopeCleaner $scopeCleaner = null ): mixed { - if (! Config::isEnabled() || ! Config::isReturnsEnabled()) { + if (! self::$isEnabled || ! self::$returnsEnabled) { return $value; } @@ -937,7 +1091,7 @@ public static function checkYield( object|string|null $thisOrClass = null, ?ScopeCleaner $scopeCleaner = null ): mixed { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return $value; } @@ -966,7 +1120,7 @@ public static function checkYield( */ public static function wrapCallable(string $function, string $paramName, mixed $callable, object|string|null $thisOrClass = null): mixed { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return $callable; } @@ -985,7 +1139,7 @@ public static function wrapCallable(string $function, string $paramName, mixed $ */ public static function wrapIterable(string $function, string $paramName, mixed $iterable, object|string|null $thisOrClass = null): mixed { - if (! Config::isEnabled()) { + if (! self::$isEnabled) { return $iterable; } From 06c6fcffa34c1c70cd1573a6625877954a89467b Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 18 Nov 2026 17:35:26 +0800 Subject: [PATCH 08/25] Refactor MemberAssignChecker and RuntimeTypeChecker for improved type validation and caching - Introduced new caching mechanisms in MemberAssignChecker for property mutation plans and substituted element contracts. - Enhanced type validation logic in MemberAssignChecker to utilize RuntimeTypeChecker for inline properties and array validation. - Updated RuntimeTypeChecker to support fast-path checks for generic return types and improved handling of inline properties. - Refactored TemplateManager to include compiled binding plan caches for generic types, optimizing template binding processes. - Added support for object generics in GenericValidator, ensuring proper validation of object types. - Enhanced TypeValidatorRegistry to streamline type validation logic for identifiers. - Added tests for handling PHP 8.1+ first-class callable syntax and parameter overwriting scenarios in ParameterTypeTrackingEliminationTest. --- .../Evaluator/ArrayLiteralEvaluator.php | 2 +- .../Ast/Elimination/StaticTypeEvaluator.php | 2 +- src/Internal/Ast/FunctionContractInjector.php | 65 +++- src/Internal/Checker/MemberAssignChecker.php | 282 +++++++++++++--- src/Internal/Checker/ReturnChecker.php | 18 +- src/Internal/Generics/TemplateManager.php | 317 +++++++++++++++++- src/Internal/RuntimeTypeChecker.php | 53 ++- src/Internal/Util/Config.php | 7 +- src/Internal/Validator/GenericValidator.php | 23 +- .../Validator/TypeValidatorRegistry.php | 6 +- .../ParameterTypeTrackingEliminationTest.php | 44 +++ 11 files changed, 722 insertions(+), 97 deletions(-) diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php index 4e9f1fa6..2fa76b92 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -380,4 +380,4 @@ private static function hasConcreteItem(Array_ $arrayExpr): bool return false; } -} \ No newline at end of file +} diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index ad3f01dc..9505e8a9 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -110,4 +110,4 @@ public static function satisfies( || ObjectEvaluator::satisfies($expr, $typeNode, $currentFile) || ScalarEvaluator::satisfies($expr, $typeNode); } -} \ No newline at end of file +} diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index e43997a9..0b47edbd 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -295,13 +295,11 @@ private static function findUnmutatedVariables(array $stmts, array $candidateNam { $unmutated = $candidateNames; - $visitor = new class ($unmutated) extends NodeVisitorAbstract { + $visitor = new class($unmutated) extends NodeVisitorAbstract { /** * @param array $unmutated */ - public function __construct(public array &$unmutated) - { - } + public function __construct(public array &$unmutated) {} public function enterNode(Node $node): ?int { @@ -325,6 +323,25 @@ public function enterNode(Node $node): ?int foreach ($node->vars as $v) { $this->disqualifyTarget($v); } + } elseif ($node instanceof Node\Stmt\Foreach_) { + $this->disqualifyTarget($node->valueVar); + if ($node->keyVar !== null) { + $this->disqualifyTarget($node->keyVar); + } + } elseif ($node instanceof Node\Stmt\Catch_) { + if ($node->var !== null && \is_string($node->var->name)) { + unset($this->unmutated[$node->var->name]); + } + } elseif ($node instanceof Node\Stmt\Static_) { + foreach ($node->vars as $sv) { + if (\is_string($sv->var->name)) { + unset($this->unmutated[$sv->var->name]); + } + } + } elseif ($node instanceof Node\Stmt\Global_) { + foreach ($node->vars as $gv) { + $this->disqualifyTarget($gv); + } } elseif ($node instanceof Node\ArrayItem && $node->byRef) { $this->disqualifyTarget($node->value); } elseif ($node instanceof Node\Expr\Closure) { @@ -334,9 +351,21 @@ public function enterNode(Node $node): ?int } } } elseif ($node instanceof Node\Expr\CallLike) { - foreach ($node->getArgs() as $arg) { - if ($arg->value instanceof Node\Expr\Variable && \is_string($arg->value->name)) { - unset($this->unmutated[$arg->value->name]); + if ( + $node instanceof Node\Expr\FuncCall + && $node->name instanceof Node\Name + && strtolower($node->name->getLast()) === 'extract' + ) { + $this->unmutated = []; + + return NodeTraverser::STOP_TRAVERSAL; + } + + if (! $node->isFirstClassCallable()) { + foreach ($node->getArgs() as $arg) { + if ($arg instanceof Node\Arg && $arg->value instanceof Node\Expr\Variable && \is_string($arg->value->name)) { + unset($this->unmutated[$arg->value->name]); + } } } } @@ -350,8 +379,12 @@ private function disqualifyTarget(Node $target): void $target = $target->var; } - if ($target instanceof Node\Expr\Variable && \is_string($target->name)) { - unset($this->unmutated[$target->name]); + if ($target instanceof Node\Expr\Variable) { + if (\is_string($target->name)) { + unset($this->unmutated[$target->name]); + } else { + $this->unmutated = []; + } } elseif ($target instanceof Node\Expr\Array_ || $target instanceof Node\Expr\List_) { foreach ($target->items as $item) { if ($item !== null) { @@ -560,7 +593,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_| private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool { - $visitor = new class () extends NodeVisitorAbstract { + $visitor = new class() extends NodeVisitorAbstract { public bool $isGen = false; public function enterNode(Node $n): ?int @@ -1109,7 +1142,7 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ( + $traverser->addVisitor(new class( $thisArg, $genContract, $currentFile, @@ -1131,8 +1164,7 @@ public function __construct( private array $byRefParams, private bool $hasSelfOut, private array $trustedParamTypes - ) { - } + ) {} public function enterNode(Node $n): int|Node|array|null { @@ -1374,7 +1406,7 @@ private static function wrapNonGeneratorReturns( self::tagPrecedingAssignments($stmts); $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ( + $traverser->addVisitor(new class( $thisArg, $isNativeVoid, $needsReturnVars, @@ -1406,8 +1438,7 @@ public function __construct( private ?TypeNode $returnTypeNode, private string $currentFile, private array $trustedParamTypes - ) { - } + ) {} public function enterNode(Node $n): int|array|null { @@ -1581,4 +1612,4 @@ public static function tagPrecedingAssignments(array $stmts): void } } } -} \ No newline at end of file +} diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index cd017b3a..32554835 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -6,12 +6,16 @@ use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; +use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use ReflectionProperty; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; +use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StructureMutator; use TypePHP\Internal\Validator\TypeValidatorRegistry; @@ -30,11 +34,40 @@ final class MemberAssignChecker private static array $refPropertyCache = []; /** - * Resets the cached reflection property registry. + * Per-property raw contract cache: + * [$className][$propName] => ?array{rawType: TypeNode, classTemplates: array, usesTemplates: bool} + * + * @var array, + * usesTemplates: bool + * }>> + */ + private static array $propertyMutationPlanCache = []; + + /** + * Substituted element contract cache keyed by template binding signature: + * [$className][$propName][$sig] => ?array{isList: bool, keyType: ?TypeNode, valueType: ?TypeNode, keyIsMixed: bool, keyIsArrayKey: bool, valueIsMixed: bool} + * + * @var array>> + */ + private static array $substitutedElementContractCache = []; + + /** + * Resets the cached reflection property and element contract registries. */ public static function reset(): void { self::$refPropertyCache = []; + self::$propertyMutationPlanCache = []; + self::$substitutedElementContractCache = []; } /** @@ -56,7 +89,7 @@ public static function check( $isObjectDimAccess = \is_object($root) && ($chain[0][0] ?? null) === 'dim'; if ( - (Config::isArrayValidationHybrid() || $isObjectDimAccess) + (RuntimeTypeChecker::$arrayValidationHybrid || $isObjectDimAccess) && ! str_contains($typeString, '{') && \count($chain) === 1 && $chain[0][0] === 'dim' @@ -121,7 +154,7 @@ public static function checkProperty( $className = \is_string($objectOrClass) ? $objectOrClass : $objectOrClass::class; - if (isset(InlineChecker::$nullPropertyCache[$className][$propName]) || ! Config::isInlinePropertiesEnabled()) { + if (isset(InlineChecker::$nullPropertyCache[$className][$propName]) || ! RuntimeTypeChecker::$inlinePropertiesEnabled) { return $value; } @@ -130,7 +163,7 @@ public static function checkProperty( if ( ( - (Config::isArrayValidationHybrid() && \is_array($currentVal) && \count($currentVal) > Config::HYBRID_SAMPLE_THRESHOLD) + (RuntimeTypeChecker::$arrayValidationHybrid && \is_array($currentVal) && \count($currentVal) > Config::HYBRID_SAMPLE_THRESHOLD) || $isObjectDimAccess ) && \count($chain) === 1 @@ -142,7 +175,6 @@ public static function checkProperty( $propName, $chain, $value, - $file, $registry ); @@ -179,68 +211,92 @@ private static function validatePropertyElementMutation( string $propName, array $chain, mixed $value, - string $file, TypeValidatorRegistry $registry ): ?ErrorMessage { try { - $rawTypeNode = DocblockParser::parseProperty($className, $propName); - if ($rawTypeNode === null) { + $contract = self::resolveElementContract($objectOrClass, $className, $propName); + if ($contract === null) { return null; } - $typeNode = $rawTypeNode; - if (\is_object($objectOrClass)) { - $allTemplates = DocblockParser::parseClassTemplates($className); - if ($allTemplates !== []) { - $boundTemplates = TemplateManager::getBoundTemplates('none', $objectOrClass, $allTemplates); - if ($boundTemplates !== []) { - $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $allTemplates); - } - } - } - $key = $chain[0][1]; - $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); - if ($typeNode instanceof GenericTypeNode) { - $base = strtolower((string) $typeNode->type); + if ($contract['isList']) { + if ($key !== null && ! \is_int($key)) { + $keyStr = \is_string($key) ? $key : ''; - if ($base === 'list' || $base === 'non-empty-list') { - if ($key !== null && ! \is_int($key)) { - return ErrorFactory::createError("Property {$className}::\${$propName} must be a list, non-integer key '{$keyStr}' given"); - } + return ErrorFactory::createError("Property {$className}::\${$propName} must be a list, non-integer key '{$keyStr}' given"); + } - $valueType = $typeNode->genericTypes[0] ?? null; - if ($valueType !== null) { - $context = "Property {$className}::\${$propName}" . ($key !== null ? "[{$key}]" : '[]'); + $valueType = $contract['valueType']; + if ($valueType !== null && ! $contract['valueIsMixed']) { + $valOk = $valueType instanceof IdentifierTypeNode && match ($valueType->name) { + 'int', 'integer' => \is_int($value), + 'string' => \is_string($value), + 'bool', 'boolean' => \is_bool($value), + 'float', 'double' => \is_float($value) || \is_int($value), + 'positive-int' => \is_int($value) && $value > 0, + 'non-empty-string' => \is_string($value) && $value !== '', + 'array-key' => \is_int($value) || \is_string($value), + 'array' => \is_array($value), + 'object' => \is_object($value), + default => \is_object($value) && ($value instanceof $valueType->name), + }; + + if (! $valOk) { + $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); + $formattedKey = $key !== null ? ($contract['quoteKey'] ? "['{$keyStr}']" : "[{$keyStr}]") : '[]'; + $context = "Property {$className}::\${$propName}" . $formattedKey; return $registry->validate($value, $valueType, $context); } - } else { - $genericCount = \count($typeNode->genericTypes); - - if ($genericCount >= 2 && $key !== null) { - $keyType = $typeNode->genericTypes[0]; - $keyErr = $registry->validate($key, $keyType, "Property {$className}::\${$propName} key"); - if ($keyErr !== null) { - return $keyErr; - } - } - - $valueType = $genericCount >= 2 - ? $typeNode->genericTypes[1] - : ($typeNode->genericTypes[0] ?? null); + } - if ($valueType !== null) { - $context = "Property {$className}::\${$propName}" . ($key !== null ? "['{$keyStr}']" : '[]'); + return null; + } - return $registry->validate($value, $valueType, $context); + $keyType = $contract['keyType']; + if ($key !== null && $keyType !== null && ! $contract['keyIsMixed']) { + $keyOk = $contract['keyIsArrayKey'] + ? (\is_int($key) || \is_string($key)) + : ($keyType instanceof IdentifierTypeNode && match ($keyType->name) { + 'int', 'integer' => \is_int($key), + 'string' => \is_string($key), + 'non-empty-string' => \is_string($key) && $key !== '', + 'positive-int' => \is_int($key) && $key > 0, + default => false, + }); + + if (! $keyOk) { + $keyErr = $registry->validate($key, $keyType, "Property {$className}::\${$propName} key"); + if ($keyErr !== null) { + return $keyErr; } } - } elseif ($typeNode instanceof ArrayTypeNode) { - $context = "Property {$className}::\${$propName}" . ($key !== null ? "[{$keyStr}]" : '[]'); + } - return $registry->validate($value, $typeNode->type, $context); + $valueType = $contract['valueType']; + if ($valueType !== null && ! $contract['valueIsMixed']) { + $valOk = $valueType instanceof IdentifierTypeNode && match ($valueType->name) { + 'int', 'integer' => \is_int($value), + 'string' => \is_string($value), + 'bool', 'boolean' => \is_bool($value), + 'float', 'double' => \is_float($value) || \is_int($value), + 'positive-int' => \is_int($value) && $value > 0, + 'non-empty-string' => \is_string($value) && $value !== '', + 'array-key' => \is_int($value) || \is_string($value), + 'array' => \is_array($value), + 'object' => \is_object($value), + default => \is_object($value) && ($value instanceof $valueType->name), + }; + + if (! $valOk) { + $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); + $formattedKey = $key !== null ? ($contract['quoteKey'] ? "['{$keyStr}']" : "[{$keyStr}]") : '[]'; + $context = "Property {$className}::\${$propName}" . $formattedKey; + + return $registry->validate($value, $valueType, $context); + } } } catch (\Throwable) { } @@ -248,6 +304,134 @@ private static function validatePropertyElementMutation( return null; } + /** + * Resolves and memoizes the substituted key/value element contract for a property mutation. + * + * @return ?array{ + * isList: bool, + * quoteKey: bool, + * keyType: ?TypeNode, + * valueType: ?TypeNode, + * keyIsMixed: bool, + * keyIsArrayKey: bool, + * valueIsMixed: bool + * } + */ + private static function resolveElementContract(mixed $objectOrClass, string $className, string $propName): ?array + { + if (! isset(self::$propertyMutationPlanCache[$className]) || ! \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) { + $rawTypeNode = DocblockParser::parseProperty($className, $propName); + if ($rawTypeNode === null) { + InlineChecker::$nullPropertyCache[$className][$propName] = true; + self::$propertyMutationPlanCache[$className][$propName] = null; + + return null; + } + + $classTemplates = DocblockParser::parseClassTemplates($className); + $usesTemplates = $classTemplates !== [] && DocblockParser::typeReferencesTemplate($rawTypeNode, $classTemplates); + + self::$propertyMutationPlanCache[$className][$propName] = [ + 'rawType' => $rawTypeNode, + 'classTemplates' => $classTemplates, + 'usesTemplates' => $usesTemplates, + ]; + } + + $propPlan = self::$propertyMutationPlanCache[$className][$propName]; + if ($propPlan === null) { + return null; + } + + $sig = ''; + $boundTemplates = []; + if ($propPlan['usesTemplates'] && \is_object($objectOrClass)) { + $boundTemplates = TemplateManager::getBoundTemplatesForInstance($objectOrClass); + if ($boundTemplates !== []) { + foreach ($boundTemplates as $k => $v) { + $sig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; + } + } + } + + if (isset(self::$substitutedElementContractCache[$className][$propName]) && \array_key_exists($sig, self::$substitutedElementContractCache[$className][$propName])) { + return self::$substitutedElementContractCache[$className][$propName][$sig]; + } + + $typeNode = $propPlan['rawType']; + if ($sig !== '') { + $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $propPlan['classTemplates']); + } + + $contract = null; + + if ($typeNode instanceof GenericTypeNode) { + $base = strtolower((string) $typeNode->type); + + if ($base === 'list' || $base === 'non-empty-list') { + $valueType = $typeNode->genericTypes[0] ?? null; + $contract = [ + 'isList' => true, + 'quoteKey' => false, + 'keyType' => null, + 'valueType' => $valueType, + 'keyIsMixed' => false, + 'keyIsArrayKey' => false, + 'valueIsMixed' => $valueType instanceof IdentifierTypeNode && strtolower($valueType->name) === 'mixed', + ]; + } else { + $genericCount = \count($typeNode->genericTypes); + $keyType = $genericCount >= 2 ? $typeNode->genericTypes[0] : null; + $valueType = $genericCount >= 2 + ? $typeNode->genericTypes[1] + : ($typeNode->genericTypes[0] ?? null); + + $contract = [ + 'isList' => false, + 'quoteKey' => true, + 'keyType' => $keyType, + 'valueType' => $valueType, + 'keyIsMixed' => $keyType instanceof IdentifierTypeNode && strtolower($keyType->name) === 'mixed', + 'keyIsArrayKey' => self::isArrayKeyType($keyType), + 'valueIsMixed' => $valueType instanceof IdentifierTypeNode && strtolower($valueType->name) === 'mixed', + ]; + } + } elseif ($typeNode instanceof ArrayTypeNode) { + $valueType = $typeNode->type; + $contract = [ + 'isList' => false, + 'quoteKey' => false, + 'keyType' => null, + 'valueType' => $valueType, + 'keyIsMixed' => false, + 'keyIsArrayKey' => false, + 'valueIsMixed' => $valueType instanceof IdentifierTypeNode && strtolower($valueType->name) === 'mixed', + ]; + } + + return self::$substitutedElementContractCache[$className][$propName][$sig] = $contract; + } + + private static function isArrayKeyType(?TypeNode $node): bool + { + if ($node instanceof IdentifierTypeNode) { + return strtolower($node->name) === 'array-key'; + } + + if ($node instanceof UnionTypeNode && \count($node->types) === 2) { + $t0 = $node->types[0]; + $t1 = $node->types[1]; + if ($t0 instanceof IdentifierTypeNode && $t1 instanceof IdentifierTypeNode) { + $n0 = strtolower($t0->name); + $n1 = strtolower($t1->name); + + return ($n0 === 'int' && $n1 === 'string') || ($n0 === 'string' && $n1 === 'int'); + } + } + + return false; + } + /** * Safely reads the current value of an instance or static property across all visibilities. */ diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index 804ea249..dd29c632 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -384,20 +384,26 @@ private static function evaluateReturn( $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + $isDynamicReturn = $contract['returnIsDynamic'] + ?? (str_contains((string) $returnTypeNode, 'static') || str_contains((string) $returnTypeNode, '$this')); + $sig = null; $boundCount = \count($boundTemplates); - if ($boundCount > 0 && $boundCount <= 2 && ! $hasConditionals && \count($aliases) === 0 && $thisObj === null) { + if ($boundCount > 0 && $boundCount <= 2 && ! $hasConditionals && \count($aliases) === 0 && ! $isDynamicReturn) { if ($boundCount === 1) { - $first = reset($boundTemplates); - $sig = $first instanceof IdentifierTypeNode ? $first->name : (string) $first; + $firstKey = (string) array_key_first($boundTemplates); + $first = $boundTemplates[$firstKey]; + $sig = $firstKey . '=' . ($first instanceof IdentifierTypeNode ? $first->name : (string) $first); } else { $sig = ''; - foreach ($boundTemplates as $v) { - $sig .= ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; + foreach ($boundTemplates as $k => $v) { + $sig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; } } - if (isset(self::$substitutedReturnCache[$function][$sig])) { + if (str_contains($sig, 'static') || str_contains($sig, '$this')) { + $sig = null; + } elseif (isset(self::$substitutedReturnCache[$function][$sig])) { $resolvedType = self::$substitutedReturnCache[$function][$sig]; } } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 877a8023..a14c2c30 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -481,6 +481,64 @@ final class TemplateManager */ private static array $propagationPlanCache = []; + /** + * Compiled binding plan cache per non-relative GenericTypeNode. + * + * @var WeakMap, + * classVariances?: array, + * templateList?: list, + * normalizedTypeArgs?: array, + * hasPropagation?: bool, + * items?: list + * }>|null + */ + private static ?WeakMap $compiledNodeBindPlanCache = null; + + /** + * Compiled binding plan cache per relative GenericTypeNode (self/static/$this) keyed by runtime class name. + * + * @var WeakMap, + * classVariances: array, + * templateList: list, + * normalizedTypeArgs: array, + * hasPropagation: bool, + * items: list + * }>>|null + */ + private static ?WeakMap $compiledRelativeNodeBindPlanCache = null; + + /** + * Fast O(1) cache of class names known to have zero inherited generic bindings or raw mappings. + * + * @var array + */ + private static array $noInheritedBindingsClasses = []; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ @@ -509,6 +567,9 @@ public static function reset(): void self::$callStackThis = []; self::$propagationStack = []; self::$propagationPlanCache = []; + self::$compiledNodeBindPlanCache = null; + self::$compiledRelativeNodeBindPlanCache = null; + self::$noInheritedBindingsClasses = []; } /** @@ -901,6 +962,18 @@ public static function getBoundTemplatesForInstance(object $instance): array return $bindings; } + /** + * Fast O(1) lookup for a single bound template on an instance without merging defaults or copying arrays. + */ + public static function getInstanceBoundTypeFast(object $instance, string $templateName): ?TypeNode + { + if (self::$instanceTemplateBindings === null) { + return null; + } + + return self::$instanceTemplateBindings[$instance][$templateName] ?? null; + } + /** * Retrieves all declared template variances ('covariant', 'contravariant', or 'invariant') for an object instance. * @@ -1089,32 +1162,121 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ */ public static function bindInstanceFromNode(object $instance, GenericTypeNode $typeNode, string $context = '', bool $forceBind = false, bool $refineOnly = false): ?ErrorMessage { - $className = (string) $typeNode->type; - if (isset(self::CONTEXT_SELF_REFERENCES[strtolower($className)])) { - $className = $instance::class; + self::$compiledNodeBindPlanCache ??= new WeakMap(); + $plan = self::$compiledNodeBindPlanCache[$typeNode] ?? null; + + if ($plan === null) { + $rawClass = (string) $typeNode->type; + if (isset(self::CONTEXT_SELF_REFERENCES[strtolower($rawClass)])) { + $plan = ['isRelative' => true]; + } else { + $plan = self::compileGenericBindingPlan($typeNode, $rawClass); + $plan['isRelative'] = false; + } + self::$compiledNodeBindPlanCache[$typeNode] = $plan; } - if (! is_a($instance, $className) || ! ClassNameValidator::isValid($className) || ! self::isRealTypeSymbol($className)) { + if ($plan['isRelative']) { + $actualClass = $instance::class; + self::$compiledRelativeNodeBindPlanCache ??= new WeakMap(); + $relativePlans = self::$compiledRelativeNodeBindPlanCache[$typeNode] ?? []; + + if (! isset($relativePlans[$actualClass])) { + $relativePlans[$actualClass] = self::compileGenericBindingPlan($typeNode, $actualClass); + self::$compiledRelativeNodeBindPlanCache[$typeNode] = $relativePlans; + } + + $plan = $relativePlans[$actualClass]; + } + + if ($plan['skip']) { return null; } - self::resolveInheritedTemplates($instance, $className); + /** @var class-string $className */ + $className = $plan['className']; + + if (! ($instance instanceof $className)) { + return null; + } + + $actualClass = $instance::class; + if (! isset(self::$noInheritedBindingsClasses[$actualClass])) { + self::resolveInheritedTemplates($instance, $className); + } + + $existingBindings = self::$instanceTemplateBindings !== null + ? (self::$instanceTemplateBindings[$instance] ?? null) + : null; + + if ( + $existingBindings !== null + && ! $forceBind + && ! $refineOnly + && ! $plan['hasPropagation'] + && self::$generatorInferredCallFrames === [] + ) { + $allFastMatched = true; + + foreach ($plan['items'] as $item) { + if (! $item['symbolValid']) { + continue; + } + + if (! $item['boundSatisfied']) { + $allFastMatched = false; + + break; + } + + $tName = $item['name']; + if (! isset($existingBindings[$tName])) { + $allFastMatched = false; + + break; + } + + if ($item['isWildcardOrMixed']) { + continue; + } + + $existingTypeNode = $existingBindings[$tName]; + $expectedTypeNode = $item['expected']; + + if ($existingTypeNode === $expectedTypeNode) { + continue; + } + + if ( + $item['identName'] !== null + && $existingTypeNode instanceof IdentifierTypeNode + && $existingTypeNode->name === $item['identName'] + ) { + continue; + } + + $allFastMatched = false; + + break; + } + + if ($allFastMatched) { + return null; + } + } try { - [$templates, $classVariances] = self::hierarchyTemplatesForClass($className); + $templates = $plan['templates']; + $classVariances = $plan['classVariances']; + $templateList = $plan['templateList']; + $normalizedTypeArgs = $plan['normalizedTypeArgs']; self::$instanceTemplateBindings ??= new WeakMap(); - $templateList = array_values($templates); - $normalizedTypeArgs = self::normalizeGenericArguments($typeNode->genericTypes, $templateList); - $candidateBindings = self::$instanceTemplateBindings[$instance] ?? []; - foreach ($templateList as $index => $templateTag) { - if (isset($normalizedTypeArgs[$index])) { - $arg = $normalizedTypeArgs[$index]; - $isWildcardOrMixed = ($arg instanceof IdentifierTypeNode && ($arg->name === '*' || strtolower($arg->name) === 'mixed')); - if (! $isWildcardOrMixed) { - $candidateBindings[$templateTag->name] = $arg; - } + + foreach ($plan['items'] as $item) { + if (! $item['isWildcardOrMixed']) { + $candidateBindings[$item['name']] = $item['expected']; } } @@ -1143,11 +1305,126 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t // Silently ignore reflection or parsing errors } - self::propagateBindingsToInstanceProperties($instance); + if ($plan['hasPropagation']) { + self::propagateBindingsToInstanceProperties($instance); + } return null; } + /** + * Pre-compiles static template metadata, argument normalization, symbol validity, + * and non-dependent upper bounds for a (GenericTypeNode, className) pair. + * + * @return array{ + * skip: bool, + * className: string, + * templates: array, + * classVariances: array, + * templateList: list, + * normalizedTypeArgs: array, + * hasPropagation: bool, + * items: list + * } + */ + private static function compileGenericBindingPlan(GenericTypeNode $typeNode, string $className): array + { + if (! ClassNameValidator::isValid($className) || ! self::isRealTypeSymbol($className)) { + return [ + 'skip' => true, + 'className' => $className, + 'templates' => [], + 'classVariances' => [], + 'templateList' => [], + 'normalizedTypeArgs' => [], + 'hasPropagation' => false, + 'items' => [], + ]; + } + + try { + [$templates, $classVariances] = self::hierarchyTemplatesForClass($className); + $templateList = array_values($templates); + $normalizedTypeArgs = self::normalizeGenericArguments($typeNode->genericTypes, $templateList); + $hasPropagation = self::propagationPlan($className) !== []; + $items = []; + + foreach ($templateList as $index => $templateTag) { + if (! isset($normalizedTypeArgs[$index])) { + continue; + } + + $expectedTypeNode = $normalizedTypeArgs[$index]; + $identName = $expectedTypeNode instanceof IdentifierTypeNode ? $expectedTypeNode->name : null; + $isWildcardOrMixed = ($identName !== null && ($identName === '*' || strtolower($identName) === 'mixed')); + + $symbolValid = true; + if ($identName !== null) { + if (str_contains($identName, '::')) { + $targetClass = explode('::', $identName, 2)[0]; + $symbolValid = self::isRealTypeSymbol($targetClass); + } else { + $symbolValid = SpecialTypeResolver::isBuiltInTypeKeyword($identName) + || self::isRealTypeSymbol($identName); + } + } elseif ($expectedTypeNode instanceof ConstTypeNode && $expectedTypeNode->constExpr instanceof ConstFetchNode && $expectedTypeNode->constExpr->className !== '') { + $symbolValid = self::isRealTypeSymbol($expectedTypeNode->constExpr->className); + } + + $boundSatisfied = true; + if ($symbolValid && $templateTag->bound !== null && ! $isWildcardOrMixed) { + if (self::isFBounded($templateTag, $className) || DocblockParser::typeReferencesTemplate($templateTag->bound, $templates)) { + $boundSatisfied = false; + } else { + $boundSatisfied = self::checkVariance($expectedTypeNode, $templateTag->bound, GenericTypeNode::VARIANCE_COVARIANT); + } + } + + $items[] = [ + 'index' => $index, + 'name' => $templateTag->name, + 'expected' => $expectedTypeNode, + 'identName' => $identName, + 'usageVariance' => $typeNode->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT, + 'isWildcardOrMixed' => $isWildcardOrMixed, + 'symbolValid' => $symbolValid, + 'boundSatisfied' => $boundSatisfied, + ]; + } + + return [ + 'skip' => false, + 'className' => $className, + 'templates' => $templates, + 'classVariances' => $classVariances, + 'templateList' => $templateList, + 'normalizedTypeArgs' => $normalizedTypeArgs, + 'hasPropagation' => $hasPropagation, + 'items' => $items, + ]; + } catch (\Throwable) { + return [ + 'skip' => false, + 'className' => $className, + 'templates' => [], + 'classVariances' => [], + 'templateList' => [], + 'normalizedTypeArgs' => [], + 'hasPropagation' => false, + 'items' => [], + ]; + } + } + /** * Checks whether a template's default type is an unspecialized placeholder (e.g. mixed or repeating its own bound). */ @@ -1852,6 +2129,10 @@ public static function resolveInheritedTemplates(object $instance, string $targe $actualClassName = $instance::class; self::$instanceTemplateBindings ??= new WeakMap(); + if (isset(self::$noInheritedBindingsClasses[$actualClassName])) { + return; + } + if (! isset(self::$classInheritedBindingsCache[$actualClassName])) { $rawBindings = []; $resolvedClassBindings = self::computeClassInheritedBindings($actualClassName, $rawBindings); @@ -1864,6 +2145,8 @@ public static function resolveInheritedTemplates(object $instance, string $targe $existing = self::$instanceTemplateBindings[$instance] ?? []; if ($cachedBindings === [] && $rawMappings === []) { + self::$noInheritedBindingsClasses[$actualClassName] = true; + return; } diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 769e8abe..7f00bf32 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -86,6 +86,10 @@ final class RuntimeTypeChecker public static bool $selfOutEnabled = true; + public static bool $inlinePropertiesEnabled = true; + + public static bool $arrayValidationHybrid = false; + private static ?TypeValidatorRegistry $registry = null; /** @@ -110,6 +114,11 @@ final class RuntimeTypeChecker */ private static array $checkedStaticProperties = []; + /** + * @var array + */ + private static array $genericReturnPlanCache = []; + /** * Resets runtime caches. */ @@ -117,6 +126,7 @@ public static function reset(): void { self::$simpleScopePlanCache = []; self::$simpleReturnPlanCache = []; + self::$genericReturnPlanCache = []; self::$hasMethodTemplatesCache = []; self::$checkedStaticProperties = []; IgnoreManager::reset(); @@ -284,7 +294,7 @@ public static function checkPropertyMemberAssign( return $value; } - if (! self::$isEnabled || ! Config::isInlinePropertiesEnabled()) { + if (! self::$isEnabled || ! self::$inlinePropertiesEnabled) { return $value; } @@ -381,7 +391,7 @@ public static function checkStaticProperty( string $file = '', ?int $line = null ): mixed { - if (! self::$isEnabled || ! Config::isInlinePropertiesEnabled()) { + if (! self::$isEnabled || ! self::$inlinePropertiesEnabled) { return $value; } @@ -890,6 +900,24 @@ public static function checkReturn(string $function, mixed $value, object|string return $value; } + // Fast-path: bare class-template return (e.g. @return T on Box::unwrap()) + if (isset(self::$genericReturnPlanCache[$function]) && \is_object($thisOrClass)) { + $genPlan = self::$genericReturnPlanCache[$function]; + if ($thisOrClass::class === $genPlan['class']) { + $boundType = TemplateManager::getInstanceBoundTypeFast($thisOrClass, $genPlan['templateName']); + if ($boundType instanceof IdentifierTypeNode) { + $tName = $boundType->name; + if (\is_object($value) && ($value instanceof $tName) && ! ($value instanceof Traversable)) { + return $value; + } + + if ($tName === 'mixed' || $tName === 'array') { + return $value; + } + } + } + } + $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); @@ -991,6 +1019,27 @@ public static function checkReturn(string $function, mixed $value, object|string return $value; } + if ( + ! $isDynamicDispatch + && $thisObj !== null + && $returnTypeNode instanceof IdentifierTypeNode + && $contract['templates'] === [] + && isset($contract['classTemplates'][$returnTypeNode->name]) + && \count($contract['aliases']) === 0 + && ! ($contract['returnHasConditional'] ?? true) + && ! $contract['returnIsDynamic'] + && ! ($contract['returnIsThis'] ?? false) + && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) + ) { + $declaringClass = str_contains($effectiveFunction, '::') ? explode('::', $effectiveFunction, 2)[0] : ''; + if ($declaringClass !== '' && $function === $effectiveFunction) { + self::$genericReturnPlanCache[$function] = [ + 'class' => $declaringClass, + 'templateName' => $returnTypeNode->name, + ]; + } + } + $vars = $vars !== null ? $vars : []; $res = ReturnChecker::checkReturn( diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index e6d59571..ef67a76a 100644 --- a/src/Internal/Util/Config.php +++ b/src/Internal/Util/Config.php @@ -878,9 +878,12 @@ public static function reset(): void RuntimeTypeChecker::$returnsEnabled = true; RuntimeTypeChecker::$paramsOutEnabled = true; RuntimeTypeChecker::$selfOutEnabled = true; + RuntimeTypeChecker::$inlinePropertiesEnabled = true; + RuntimeTypeChecker::$arrayValidationHybrid = false; DocblockParser::reset(); ParamChecker::reset(); + MemberAssignChecker::reset(); ReturnChecker::reset(); TemplateManager::reset(); HierarchyResolver::reset(); @@ -959,6 +962,8 @@ private static function syncFlags(array $config): void RuntimeTypeChecker::$returnsEnabled = self::$returns; RuntimeTypeChecker::$paramsOutEnabled = self::$params && self::$paramsOut; RuntimeTypeChecker::$selfOutEnabled = self::$selfOut; + RuntimeTypeChecker::$inlinePropertiesEnabled = self::$inlineProperties; + RuntimeTypeChecker::$arrayValidationHybrid = (self::$arrayValidation === 'hybrid'); } private static function probeProcessEnvOverrides(): void @@ -992,4 +997,4 @@ private static function resolveEnabledOverride(string $key, ?string $cachedProce return null; } -} \ No newline at end of file +} diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 6810211f..c061e52a 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -214,6 +214,24 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return $this->validateIntMaskOf($value, $genericNode, $context, $isSensitive); } + if ($kind === self::KIND_OBJECT_GENERIC) { + /** @var class-string|null $targetClass */ + $targetClass = $compiled[1]; + if ($targetClass === null) { + return null; + } + + if (! \is_object($value)) { + return ErrorFactory::createError($context . ' must be an object of type ' . $targetClass . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + if (! ($value instanceof $targetClass)) { + return ErrorFactory::createError($context . ' must be an instance of ' . $targetClass . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + return TemplateManager::bindInstanceFromNode($value, $genericNode, $context); + } + return $this->validateObjectGeneric($value, $genericNode, $context, $isSensitive); } @@ -244,7 +262,10 @@ private function compileGeneric(GenericTypeNode $node): array 'value-of' => [self::KIND_VALUE_OF, null], 'int-mask' => [self::KIND_INT_MASK, null], 'int-mask-of' => [self::KIND_INT_MASK_OF, null], - default => [self::KIND_OBJECT_GENERIC, (string) $node->type], + default => [ + self::KIND_OBJECT_GENERIC, + ClassNameValidator::isValid($typeName) ? $typeName : null, + ], }; } diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index 3d88f0af..ca868c79 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -68,7 +68,8 @@ public function __construct() public function validate(mixed $value, TypeNode $node, string $context = '', bool $isSensitive = false): ?ErrorMessage { if ($node instanceof IdentifierTypeNode) { - $ok = match ($node->name) { + $name = $node->name; + $ok = match ($name) { 'int', 'integer' => \is_int($value), 'string' => \is_string($value), 'positive-int' => \is_int($value) && $value > 0, @@ -89,7 +90,8 @@ public function validate(mixed $value, TypeNode $node, string $context = '', boo 'true' => $value === true, 'false' => $value === false, 'scalar' => \is_scalar($value), - default => false, + 'object' => \is_object($value), + default => \is_object($value) && ($value instanceof $name), }; if ($ok) { diff --git a/tests/Internal/Ast/Elimination/ParameterTypeTrackingEliminationTest.php b/tests/Internal/Ast/Elimination/ParameterTypeTrackingEliminationTest.php index f171a057..eba3e1f5 100644 --- a/tests/Internal/Ast/Elimination/ParameterTypeTrackingEliminationTest.php +++ b/tests/Internal/Ast/Elimination/ParameterTypeTrackingEliminationTest.php @@ -7,6 +7,50 @@ use TypePHP\Internal\Io\StreamWrapper; describe('Compile-Time Return Elimination via Parameter Type Tracking', function () { + test('handles PHP 8.1+ first-class callable syntax without VariadicPlaceholder warnings', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::setupScope') + ->and($transformed)->not()->toContain('RuntimeTypeChecker::checkReturn') + ->and($transformed)->toContain('return $text;') + ; + }); + + test('retains checkReturn when parameter is overwritten by foreach or catch variable', function () { + $source = <<<'PHP' +toContain('RuntimeTypeChecker::checkReturn'); + }); + test('eliminates checkReturn when method returns an array shape containing unmutated validated parameters', function () { $source = <<<'PHP' Date: Thu, 19 Nov 2026 13:34:03 +0800 Subject: [PATCH 09/25] Enhance MemberAssignChecker with improved contract validation and generics performance --- src/Internal/Ast/FunctionContractInjector.php | 18 +- src/Internal/Checker/GeneratorChecker.php | 392 ++++++++++-- src/Internal/Checker/MemberAssignChecker.php | 574 +++++++++++++----- src/Internal/Generics/TemplateManager.php | 57 +- src/Internal/RuntimeTypeChecker.php | 20 +- 5 files changed, 828 insertions(+), 233 deletions(-) diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 0b47edbd..59dd940b 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -295,11 +295,13 @@ private static function findUnmutatedVariables(array $stmts, array $candidateNam { $unmutated = $candidateNames; - $visitor = new class($unmutated) extends NodeVisitorAbstract { + $visitor = new class ($unmutated) extends NodeVisitorAbstract { /** * @param array $unmutated */ - public function __construct(public array &$unmutated) {} + public function __construct(public array &$unmutated) + { + } public function enterNode(Node $node): ?int { @@ -593,7 +595,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_| private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool { - $visitor = new class() extends NodeVisitorAbstract { + $visitor = new class () extends NodeVisitorAbstract { public bool $isGen = false; public function enterNode(Node $n): ?int @@ -1142,7 +1144,7 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class( + $traverser->addVisitor(new class ( $thisArg, $genContract, $currentFile, @@ -1164,7 +1166,8 @@ public function __construct( private array $byRefParams, private bool $hasSelfOut, private array $trustedParamTypes - ) {} + ) { + } public function enterNode(Node $n): int|Node|array|null { @@ -1406,7 +1409,7 @@ private static function wrapNonGeneratorReturns( self::tagPrecedingAssignments($stmts); $traverser = new NodeTraverser(); - $traverser->addVisitor(new class( + $traverser->addVisitor(new class ( $thisArg, $isNativeVoid, $needsReturnVars, @@ -1438,7 +1441,8 @@ public function __construct( private ?TypeNode $returnTypeNode, private string $currentFile, private array $trustedParamTypes - ) {} + ) { + } public function enterNode(Node $n): int|array|null { diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index 1ce0a272..6e3d191d 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -4,10 +4,12 @@ namespace TypePHP\Internal\Checker; +use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Internal\Ast\ScopeCleaner; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\TypeFormatter; @@ -15,13 +17,55 @@ use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Validator\TypeValidatorRegistry; +use WeakMap; /** * @internal Evaluates generator yield, send (TSend), and return (TReturn) type validations. */ final class GeneratorChecker { + private const OP_NONE = 0; + + private const OP_INT = 1; + + private const OP_STRING = 2; + + private const OP_BOOL = 3; + + private const OP_FLOAT = 4; + + private const OP_POSITIVE_INT = 5; + + private const OP_NON_EMPTY_STRING = 6; + + private const OP_ARRAY_KEY = 7; + + private const OP_ARRAY = 8; + + private const OP_OBJECT = 9; + + private const OP_CLASS = 10; + + private const OP_MASK = 11; + + private const OP_FALLBACK = 12; + + private const BIT_INT = 1; + + private const BIT_STRING = 2; + + private const BIT_BOOL = 4; + + private const BIT_FLOAT = 8; + + private const BIT_OBJECT = 16; + + private const BIT_NULL = 32; + + private const BIT_ARRAY = 64; + /** * O(1) Fast-path cache for generators determined to have no return contracts. * @@ -30,26 +74,54 @@ final class GeneratorChecker private static array $noContractCache = []; /** - * Cache for resolved yield & send types of static / non-generic generators: - * [$function] => array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode}. + * Per-function static plan cache avoiding repeated DocblockParser/ConditionalChecker calls. + * + * @var array, + * aliases: array, + * hasGenerics: bool, + * hasMethodTemplates: bool, + * hasAliases: bool, + * hasConditionals: bool, + * isDynamic: bool + * }> + */ + private static array $generatorPlanCache = []; + + /** + * Cache for resolved yield & send types of non-generic generators: + * [$effectiveFunction] => compiled tuple. * - * @var array + * @var array */ private static array $staticYieldTypeCache = []; /** * 2D Cache for resolved yield & send types of generic generators: - * [$function][$templateSignature] => array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode}. + * [$effectiveFunction][$templateSignature] => compiled tuple. * - * @var array> + * @var array> */ private static array $genericYieldTypeCache = []; + /** + * Per-instance yield contract cache keyed by object identity and raw bindings equality. + * + * @var WeakMap, + * types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed} + * }>>|null + */ + private static ?WeakMap $instanceYieldCache = null; + public static function reset(): void { self::$noContractCache = []; + self::$generatorPlanCache = []; self::$staticYieldTypeCache = []; self::$genericYieldTypeCache = []; + self::$instanceYieldCache = null; } /** @@ -60,13 +132,15 @@ public static function checkSend( mixed $sendValue, TypeValidatorRegistry $registry, object|string|null $thisOrClass = null, - ?ScopeCleaner $scopeCleaner = null + ?ScopeCleaner $scopeCleaner = null, + string $effectiveFunction = '' ): mixed { if ($sendValue === null) { return null; } - $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry, $scopeCleaner); + $targetFunction = $effectiveFunction !== '' ? $effectiveFunction : $function; + $types = self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $sendValue; } @@ -76,7 +150,7 @@ public static function checkSend( return $sendValue; } - $err = $registry->validate($sendValue, $sendTypeNode, "$function(): Generator sent value (TSend)"); + $err = $registry->validate($sendValue, $sendTypeNode, "$targetFunction(): Generator sent value (TSend)"); return $err ?? $sendValue; } @@ -90,26 +164,63 @@ public static function checkYield( mixed $value, TypeValidatorRegistry $registry, object|string|null $thisOrClass = null, - ?ScopeCleaner $scopeCleaner = null + ?ScopeCleaner $scopeCleaner = null, + string $effectiveFunction = '' ): mixed { - $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry, $scopeCleaner); + $targetFunction = $effectiveFunction !== '' ? $effectiveFunction : $function; + $types = self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $value; } - [$keyTypeNode, $itemTypeNode] = $types; - - if ($key !== null && $keyTypeNode !== null) { - $err = $registry->validate($key, $keyTypeNode, "$function(): Return iterator key"); - if ($err !== null) { - return $err; + $keyOp = $types[4]; + if ($key !== null && $keyOp !== self::OP_NONE) { + $keyExtra = $types[5]; + $keyOk = match ($keyOp) { + self::OP_INT => \is_int($key), + self::OP_STRING => \is_string($key), + self::OP_ARRAY_KEY => \is_int($key) || \is_string($key), + self::OP_POSITIVE_INT => \is_int($key) && $key > 0, + self::OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', + self::OP_BOOL => \is_bool($key), + self::OP_FLOAT => \is_float($key) || \is_int($key), + self::OP_OBJECT => \is_object($key), + self::OP_CLASS => \is_object($key) && ($key instanceof $keyExtra), + self::OP_MASK => self::matchesMask($key, (int) $keyExtra), + default => false, + }; + + if (! $keyOk && $types[0] !== null) { + $err = $registry->validate($key, $types[0], "$targetFunction(): Return iterator key"); + if ($err !== null) { + return $err; + } } } - if ($itemTypeNode !== null) { - $err = $registry->validate($value, $itemTypeNode, "$function(): Return iterator value"); - if ($err !== null) { - return $err; + $valOp = $types[6]; + if ($valOp !== self::OP_NONE) { + $valExtra = $types[7]; + $valOk = match ($valOp) { + self::OP_STRING => \is_string($value), + self::OP_INT => \is_int($value), + self::OP_BOOL => \is_bool($value), + self::OP_FLOAT => \is_float($value) || \is_int($value), + self::OP_POSITIVE_INT => \is_int($value) && $value > 0, + self::OP_NON_EMPTY_STRING => \is_string($value) && $value !== '', + self::OP_ARRAY_KEY => \is_int($value) || \is_string($value), + self::OP_ARRAY => \is_array($value), + self::OP_OBJECT => \is_object($value), + self::OP_CLASS => \is_object($value) && ($value instanceof $valExtra), + self::OP_MASK => self::matchesMask($value, (int) $valExtra), + default => false, + }; + + if (! $valOk && $types[1] !== null) { + $err = $registry->validate($value, $types[1], "$targetFunction(): Return iterator value"); + if ($err !== null) { + return $err; + } } } @@ -124,9 +235,11 @@ public static function checkReturn( mixed $value, TypeValidatorRegistry $registry, object|string|null $thisOrClass = null, - ?ScopeCleaner $scopeCleaner = null + ?ScopeCleaner $scopeCleaner = null, + string $effectiveFunction = '' ): mixed { - $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry, $scopeCleaner); + $targetFunction = $effectiveFunction !== '' ? $effectiveFunction : $function; + $types = self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $value; } @@ -138,21 +251,21 @@ public static function checkReturn( if ($returnTypeNode instanceof IdentifierTypeNode && strtolower($returnTypeNode->name) === 'void') { if ($value !== null) { - return ErrorFactory::createError("$function(): Generator return value must be of type void, " . TypeFormatter::formatGivenValue($value) . ' returned'); + return ErrorFactory::createError("$targetFunction(): Generator return value must be of type void, " . TypeFormatter::formatGivenValue($value) . ' returned'); } return null; } - $err = $registry->validate($value, $returnTypeNode, "$function(): Generator return value (TReturn)"); + $err = $registry->validate($value, $returnTypeNode, "$targetFunction(): Generator return value (TReturn)"); return $err ?? $value; } /** - * Resolves and caches the generator's yielded key, value, and sent types in memory. + * Resolves and caches the generator's yielded key, value, sent, and return types in memory. * - * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode}|null + * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}|null */ private static function resolveYieldAndSendTypes( string $function, @@ -160,7 +273,7 @@ private static function resolveYieldAndSendTypes( ?TypeValidatorRegistry $registry = null, ?ScopeCleaner $scopeCleaner = null ): ?array { - if ($scopeCleaner === null && isset(self::$noContractCache[$function])) { + if (isset(self::$noContractCache[$function])) { return null; } @@ -168,50 +281,98 @@ private static function resolveYieldAndSendTypes( return self::$staticYieldTypeCache[$function]; } - $contract = DocblockParser::parse($function); - $returnTypeNode = $contract['return'] ?? null; + $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - if ($returnTypeNode === null) { - self::$noContractCache[$function] = true; + if (! isset(self::$generatorPlanCache[$function])) { + $contract = DocblockParser::parse($function); + $returnTypeNode = $contract['return'] ?? null; - return null; - } + if ($returnTypeNode === null) { + self::$noContractCache[$function] = true; - $allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; - $aliases = $contract['aliases'] ?? []; - $hasGenerics = \count($allTemplates) > 0; - $hasAliases = \count($aliases) > 0; - $hasConditionals = ConditionalChecker::containsConditional($returnTypeNode); - $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; + return null; + } + + $allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; + $aliases = $contract['aliases'] ?? []; + $hasGenerics = $allTemplates !== []; + $hasMethodTemplates = ($contract['templates'] ?? []) !== []; + $hasAliases = $aliases !== []; + $hasConditionals = $contract['returnHasConditional'] ?? ConditionalChecker::containsConditional($returnTypeNode); + $isDynamic = $contract['returnIsDynamic'] ?? (str_contains((string) $returnTypeNode, 'static') || str_contains((string) $returnTypeNode, '$this')); - if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && $thisObj === null && $scopeCleaner === null) { - $resolvedNode = SpecialTypeResolver::resolve($returnTypeNode, $function, null); + if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && ! $isDynamic) { + $resolvedNode = SpecialTypeResolver::resolve($returnTypeNode, $function, null); - return self::$staticYieldTypeCache[$function] = self::extractYieldTypes($resolvedNode); + return self::$staticYieldTypeCache[$function] = self::compileYieldTypes($resolvedNode); + } + + self::$generatorPlanCache[$function] = [ + 'returnType' => $returnTypeNode, + 'allTemplates' => $allTemplates, + 'aliases' => $aliases, + 'hasGenerics' => $hasGenerics, + 'hasMethodTemplates' => $hasMethodTemplates, + 'hasAliases' => $hasAliases, + 'hasConditionals' => $hasConditionals, + 'isDynamic' => $isDynamic, + ]; } + $plan = self::$generatorPlanCache[$function]; + $returnTypeNode = $plan['returnType']; + $allTemplates = $plan['allTemplates']; + $aliases = $plan['aliases']; + + $canUseInstanceCache = $thisObj !== null + && $scopeCleaner === null + && ! $plan['hasMethodTemplates'] + && ! $plan['hasAliases'] + && ! $plan['hasConditionals'] + && ! $plan['isDynamic']; + $boundTemplates = []; if ($scopeCleaner !== null && $scopeCleaner->boundTemplates !== []) { $boundTemplates = $scopeCleaner->boundTemplates; - } elseif ($hasGenerics) { - $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $allTemplates); + } elseif ($plan['hasGenerics']) { + $boundTemplates = ($thisObj !== null && ! $plan['hasMethodTemplates']) + ? TemplateManager::getInstanceBindingsFast($thisObj) + : TemplateManager::getBoundTemplates($function, $thisOrClass, $allTemplates); + } + + if ($canUseInstanceCache) { + self::$instanceYieldCache ??= new WeakMap(); + $cachedEntry = self::$instanceYieldCache[$thisObj][$function] ?? null; + if ($cachedEntry !== null && $cachedEntry['bindings'] === $boundTemplates) { + return $cachedEntry['types']; + } } $sig = null; - $boundCount = \count($boundTemplates); - if ($boundCount > 0 && $boundCount <= 2 && ! $hasAliases && ! $hasConditionals && $thisObj === null && $scopeCleaner === null) { - if ($boundCount === 1) { - $first = reset($boundTemplates); - $sig = $first instanceof IdentifierTypeNode ? $first->name : (string) $first; - } else { + if (! $plan['hasAliases'] && ! $plan['hasConditionals'] && ! $plan['isDynamic'] && $scopeCleaner === null) { + if ($boundTemplates === []) { + $sig = ''; + } elseif (\count($boundTemplates) === 1) { + $firstKey = (string) array_key_first($boundTemplates); + $first = $boundTemplates[$firstKey]; + $sig = $firstKey . '=' . ($first instanceof IdentifierTypeNode ? $first->name : (string) $first); + } elseif (\count($boundTemplates) <= 3) { $sig = ''; - foreach ($boundTemplates as $v) { - $sig .= ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; + foreach ($boundTemplates as $k => $v) { + $sig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; } } - if (isset(self::$genericYieldTypeCache[$function][$sig])) { - return self::$genericYieldTypeCache[$function][$sig]; + if ($sig !== null && isset(self::$genericYieldTypeCache[$function][$sig])) { + $types = self::$genericYieldTypeCache[$function][$sig]; + if ($canUseInstanceCache) { + /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}}> $mapEntry */ + $mapEntry = self::$instanceYieldCache[$thisObj] ?? []; + $mapEntry[$function] = ['bindings' => $boundTemplates, 'types' => $types]; + self::$instanceYieldCache[$thisObj] = $mapEntry; + } + + return $types; } } @@ -219,34 +380,43 @@ private static function resolveYieldAndSendTypes( $returnTypeNode = $aliases[$returnTypeNode->name]; } - if ($hasConditionals && $registry !== null) { + if ($plan['hasConditionals'] && $registry !== null) { $returnTypeNode = ConditionalChecker::resolve($returnTypeNode, [], $boundTemplates, $registry, $function); } - if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) { + if ($boundTemplates !== [] || $allTemplates !== []) { $returnTypeNode = TemplateSubstitutor::substitute($returnTypeNode, $boundTemplates, $allTemplates); $returnTypeNode = SpecialTypeResolver::resolve($returnTypeNode, $function, $thisObj); + } elseif ($plan['isDynamic']) { + $returnTypeNode = SpecialTypeResolver::resolve($returnTypeNode, $function, $thisObj); } if (ConditionalChecker::containsConditional($returnTypeNode) && $registry !== null) { $returnTypeNode = ConditionalChecker::resolve($returnTypeNode, [], $boundTemplates, $registry, $function); } - $types = self::extractYieldTypes($returnTypeNode); + $types = self::compileYieldTypes($returnTypeNode); if ($sig !== null) { self::$genericYieldTypeCache[$function][$sig] = $types; } + if ($canUseInstanceCache) { + /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}}> $mapEntry */ + $mapEntry = self::$instanceYieldCache[$thisObj] ?? []; + $mapEntry[$function] = ['bindings' => $boundTemplates, 'types' => $types]; + self::$instanceYieldCache[$thisObj] = $mapEntry; + } + return $types; } /** - * Extracts yielded key, item, sent (TSend), and return (TReturn) TypeNodes from a resolved generator/array AST node. + * Extracts and precompiles yielded key, item, sent (TSend), and return (TReturn) contracts. * - * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode} + * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed} */ - private static function extractYieldTypes(TypeNode $returnTypeNode): array + private static function compileYieldTypes(TypeNode $returnTypeNode): array { $itemTypeNode = null; $keyTypeNode = null; @@ -274,6 +444,106 @@ private static function extractYieldTypes(TypeNode $returnTypeNode): array $itemTypeNode = $returnTypeNode->type; } - return [$keyTypeNode, $itemTypeNode, $sendTypeNode, $generatorReturnTypeNode]; + if ($keyTypeNode instanceof IdentifierTypeNode && strtolower($keyTypeNode->name) === 'mixed') { + $keyTypeNode = null; + } + + if ($itemTypeNode instanceof IdentifierTypeNode && strtolower($itemTypeNode->name) === 'mixed') { + $itemTypeNode = null; + } + + [$keyOp, $keyExtra] = self::compileCheckOp($keyTypeNode); + [$valOp, $valExtra] = self::compileCheckOp($itemTypeNode); + + return [$keyTypeNode, $itemTypeNode, $sendTypeNode, $generatorReturnTypeNode, $keyOp, $keyExtra, $valOp, $valExtra]; + } + + /** + * @return array{0: int, 1: mixed} + */ + private static function compileCheckOp(?TypeNode $typeNode): array + { + if ($typeNode === null) { + return [self::OP_NONE, null]; + } + + if ($typeNode instanceof IdentifierTypeNode) { + $name = $typeNode->name; + $lower = strtolower($name); + + return match ($lower) { + 'mixed' => [self::OP_NONE, null], + 'int', 'integer' => [self::OP_INT, null], + 'string' => [self::OP_STRING, null], + 'bool', 'boolean' => [self::OP_BOOL, null], + 'float', 'double' => [self::OP_FLOAT, null], + 'positive-int' => [self::OP_POSITIVE_INT, null], + 'non-empty-string' => [self::OP_NON_EMPTY_STRING, null], + 'array-key' => [self::OP_ARRAY_KEY, null], + 'array' => [self::OP_ARRAY, null], + 'object' => [self::OP_OBJECT, null], + default => (ClassNameValidator::isValid($name) && (class_exists($name, false) || interface_exists($name, false))) + ? [self::OP_CLASS, $name] + : [self::OP_FALLBACK, null], + }; + } + + if ($typeNode instanceof UnionTypeNode) { + $mask = 0; + foreach ($typeNode->types as $member) { + if (! ($member instanceof IdentifierTypeNode)) { + return [self::OP_FALLBACK, null]; + } + + $bit = match (strtolower($member->name)) { + 'int', 'integer' => self::BIT_INT, + 'string' => self::BIT_STRING, + 'bool', 'boolean' => self::BIT_BOOL, + 'float', 'double' => self::BIT_FLOAT, + 'object' => self::BIT_OBJECT, + 'null' => self::BIT_NULL, + 'array' => self::BIT_ARRAY, + 'array-key' => self::BIT_INT | self::BIT_STRING, + default => 0, + }; + + if ($bit === 0) { + return [self::OP_FALLBACK, null]; + } + + $mask |= $bit; + } + + return $mask !== 0 ? [self::OP_MASK, $mask] : [self::OP_FALLBACK, null]; + } + + return [self::OP_FALLBACK, null]; + } + + private static function matchesMask(mixed $value, int $mask): bool + { + if (\is_string($value)) { + return ($mask & self::BIT_STRING) !== 0; + } + if (\is_int($value)) { + return ($mask & (self::BIT_INT | self::BIT_FLOAT)) !== 0; + } + if (\is_object($value)) { + return ($mask & self::BIT_OBJECT) !== 0; + } + if (\is_bool($value)) { + return ($mask & self::BIT_BOOL) !== 0; + } + if (\is_float($value)) { + return ($mask & self::BIT_FLOAT) !== 0; + } + if ($value === null) { + return ($mask & self::BIT_NULL) !== 0; + } + if (\is_array($value)) { + return ($mask & self::BIT_ARRAY) !== 0; + } + + return false; } } diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 32554835..72159a8b 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -4,11 +4,13 @@ namespace TypePHP\Internal\Checker; +use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use ReflectionNamedType; use ReflectionProperty; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; @@ -16,15 +18,55 @@ use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\RuntimeTypeChecker; +use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StructureMutator; use TypePHP\Internal\Validator\TypeValidatorRegistry; +use WeakMap; /** * @internal Evaluates array key/dimension and object shape property member assignments. */ final class MemberAssignChecker { + private const OP_NONE = 0; + + private const OP_INT = 1; + + private const OP_STRING = 2; + + private const OP_BOOL = 3; + + private const OP_FLOAT = 4; + private const OP_POSITIVE_INT = 5; + + private const OP_NON_EMPTY_STRING = 6; + private const OP_ARRAY_KEY = 7; + + private const OP_ARRAY = 8; + + private const OP_OBJECT = 9; + + private const OP_CLASS = 10; + + private const OP_MASK = 11; + + private const OP_FALLBACK = 12; + + private const BIT_INT = 1; + + private const BIT_STRING = 2; + + private const BIT_BOOL = 4; + + private const BIT_FLOAT = 8; + + private const BIT_OBJECT = 16; + + private const BIT_NULL = 32; + + private const BIT_ARRAY = 64; + /** * In-memory 2D cache for ReflectionProperty instances: * [$className][$propName] => ?ReflectionProperty (null = non-declared/dynamic property) @@ -35,31 +77,60 @@ final class MemberAssignChecker /** * Per-property raw contract cache: - * [$className][$propName] => ?array{rawType: TypeNode, classTemplates: array, usesTemplates: bool} + * [$className][$propName] => ?array{ + * rawType: TypeNode, + * classTemplates: array, + * usesTemplates: bool, + * isNativeNonNullArray: bool, + * isMagicOrMissing: bool + * } * * @var array, - * usesTemplates: bool + * classTemplates: array, + * usesTemplates: bool, + * isNativeNonNullArray: bool, + * isMagicOrMissing: bool * }>> */ private static array $propertyMutationPlanCache = []; /** * Substituted element contract cache keyed by template binding signature: - * [$className][$propName][$sig] => ?array{isList: bool, keyType: ?TypeNode, valueType: ?TypeNode, keyIsMixed: bool, keyIsArrayKey: bool, valueIsMixed: bool} + * [$className][$propName][$sig] => ?array{...} * * @var array>> */ private static array $substitutedElementContractCache = []; + /** + * Per-instance contract cache keyed by object identity and raw bindings equality. + * + * @var WeakMap, + * contracts: array + * }>|null + */ + private static ?WeakMap $instanceContractCache = null; + /** * Resets the cached reflection property and element contract registries. */ @@ -68,6 +139,7 @@ public static function reset(): void self::$refPropertyCache = []; self::$propertyMutationPlanCache = []; self::$substitutedElementContractCache = []; + self::$instanceContractCache = null; } /** @@ -146,7 +218,7 @@ public static function checkProperty( array $chain, mixed $value, string $file, - TypeValidatorRegistry $registry + ?TypeValidatorRegistry $registry = null ): mixed { if (! \is_object($objectOrClass) && ! \is_string($objectOrClass)) { return $value; @@ -158,6 +230,38 @@ public static function checkProperty( return $value; } + if (\count($chain) === 1 && $chain[0][0] === 'dim') { + $propPlan = self::getPropertyMutationPlan($className, $propName); + if ($propPlan === null) { + return $value; + } + + if ( + RuntimeTypeChecker::$arrayValidationHybrid + && ! $propPlan['isMagicOrMissing'] + && $propPlan['isNativeNonNullArray'] + && \is_object($objectOrClass) + ) { + $contract = self::resolveElementContractFromPlan($objectOrClass, $className, $propName, $propPlan); + if ($contract !== null && (! $contract['isList'] || $chain[0][1] === null)) { + $directErr = self::validatePropertyElementMutationWithContract( + $className, + $propName, + $chain[0][1], + $value, + $contract, + $registry + ); + + if ($directErr instanceof ErrorMessage) { + return $directErr; + } + + return $value; + } + } + } + $currentVal = self::readPropertyValue($objectOrClass, $className, $propName); $isObjectDimAccess = \is_object($currentVal) && ($chain[0][0] ?? null) === 'dim'; @@ -169,17 +273,20 @@ public static function checkProperty( && \count($chain) === 1 && $chain[0][0] === 'dim' ) { - $directErr = self::validatePropertyElementMutation( - $objectOrClass, - $className, - $propName, - $chain, - $value, - $registry - ); - - if ($directErr instanceof ErrorMessage) { - return $directErr; + $contract = self::resolveElementContract($objectOrClass, $className, $propName); + if ($contract !== null) { + $directErr = self::validatePropertyElementMutationWithContract( + $className, + $propName, + $chain[0][1], + $value, + $contract, + $registry + ); + + if ($directErr instanceof ErrorMessage) { + return $directErr; + } } return $value; @@ -191,7 +298,13 @@ public static function checkProperty( $copy = StructureMutator::mutateCopy($currentVal, $chain, $value); - $res = InlineChecker::checkProperty($copy, $objectOrClass, $propName, $file, $registry); + $res = InlineChecker::checkProperty( + $copy, + $objectOrClass, + $propName, + $file, + $registry ?? RuntimeTypeChecker::getRegistry() + ); if ($res instanceof ErrorMessage) { return $res; @@ -201,101 +314,82 @@ public static function checkProperty( } /** - * Directly validates a single element appended/assigned to a large property array or generic ArrayAccess object in O(1). + * Directly validates a single element appended/assigned to a property array or generic ArrayAccess object in O(1). * - * @param list $chain + * @param array{ + * isList: bool, + * quoteKey: bool, + * keyType: ?TypeNode, + * valueType: ?TypeNode, + * keyOp: int, + * keyExtra: mixed, + * valOp: int, + * valExtra: mixed + * } $contract */ - private static function validatePropertyElementMutation( - mixed $objectOrClass, + private static function validatePropertyElementMutationWithContract( string $className, string $propName, - array $chain, + mixed $key, mixed $value, - TypeValidatorRegistry $registry + array $contract, + ?TypeValidatorRegistry $registry ): ?ErrorMessage { try { - $contract = self::resolveElementContract($objectOrClass, $className, $propName); - if ($contract === null) { - return null; - } - - $key = $chain[0][1]; - if ($contract['isList']) { if ($key !== null && ! \is_int($key)) { $keyStr = \is_string($key) ? $key : ''; return ErrorFactory::createError("Property {$className}::\${$propName} must be a list, non-integer key '{$keyStr}' given"); } + } elseif ($key !== null && $contract['keyOp'] !== self::OP_NONE) { + $keyExtra = $contract['keyExtra']; + $keyOk = match ($contract['keyOp']) { + self::OP_INT => \is_int($key), + self::OP_STRING => \is_string($key), + self::OP_ARRAY_KEY => \is_int($key) || \is_string($key), + self::OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', + self::OP_POSITIVE_INT => \is_int($key) && $key > 0, + self::OP_MASK => self::matchesMask($key, (int) $keyExtra), + self::OP_OBJECT => \is_object($key), + self::OP_CLASS => \is_object($key) && ($key instanceof $keyExtra), + default => false, + }; - $valueType = $contract['valueType']; - if ($valueType !== null && ! $contract['valueIsMixed']) { - $valOk = $valueType instanceof IdentifierTypeNode && match ($valueType->name) { - 'int', 'integer' => \is_int($value), - 'string' => \is_string($value), - 'bool', 'boolean' => \is_bool($value), - 'float', 'double' => \is_float($value) || \is_int($value), - 'positive-int' => \is_int($value) && $value > 0, - 'non-empty-string' => \is_string($value) && $value !== '', - 'array-key' => \is_int($value) || \is_string($value), - 'array' => \is_array($value), - 'object' => \is_object($value), - default => \is_object($value) && ($value instanceof $valueType->name), - }; - - if (! $valOk) { - $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); - $formattedKey = $key !== null ? ($contract['quoteKey'] ? "['{$keyStr}']" : "[{$keyStr}]") : '[]'; - $context = "Property {$className}::\${$propName}" . $formattedKey; - - return $registry->validate($value, $valueType, $context); - } - } - - return null; - } - - $keyType = $contract['keyType']; - if ($key !== null && $keyType !== null && ! $contract['keyIsMixed']) { - $keyOk = $contract['keyIsArrayKey'] - ? (\is_int($key) || \is_string($key)) - : ($keyType instanceof IdentifierTypeNode && match ($keyType->name) { - 'int', 'integer' => \is_int($key), - 'string' => \is_string($key), - 'non-empty-string' => \is_string($key) && $key !== '', - 'positive-int' => \is_int($key) && $key > 0, - default => false, - }); - - if (! $keyOk) { - $keyErr = $registry->validate($key, $keyType, "Property {$className}::\${$propName} key"); + if (! $keyOk && $contract['keyType'] !== null) { + $registry ??= RuntimeTypeChecker::getRegistry(); + $keyErr = $registry->validate($key, $contract['keyType'], "Property {$className}::\${$propName} key"); if ($keyErr !== null) { return $keyErr; } } } - $valueType = $contract['valueType']; - if ($valueType !== null && ! $contract['valueIsMixed']) { - $valOk = $valueType instanceof IdentifierTypeNode && match ($valueType->name) { - 'int', 'integer' => \is_int($value), - 'string' => \is_string($value), - 'bool', 'boolean' => \is_bool($value), - 'float', 'double' => \is_float($value) || \is_int($value), - 'positive-int' => \is_int($value) && $value > 0, - 'non-empty-string' => \is_string($value) && $value !== '', - 'array-key' => \is_int($value) || \is_string($value), - 'array' => \is_array($value), - 'object' => \is_object($value), - default => \is_object($value) && ($value instanceof $valueType->name), + $valOp = $contract['valOp']; + if ($valOp !== self::OP_NONE) { + $valExtra = $contract['valExtra']; + $valOk = match ($valOp) { + self::OP_INT => \is_int($value), + self::OP_STRING => \is_string($value), + self::OP_BOOL => \is_bool($value), + self::OP_FLOAT => \is_float($value) || \is_int($value), + self::OP_POSITIVE_INT => \is_int($value) && $value > 0, + self::OP_NON_EMPTY_STRING => \is_string($value) && $value !== '', + self::OP_ARRAY_KEY => \is_int($value) || \is_string($value), + self::OP_ARRAY => \is_array($value), + self::OP_OBJECT => \is_object($value), + self::OP_CLASS => \is_object($value) && ($value instanceof $valExtra), + self::OP_MASK => self::matchesMask($value, (int) $valExtra), + default => false, }; - if (! $valOk) { + if (! $valOk && $contract['valueType'] !== null) { $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); $formattedKey = $key !== null ? ($contract['quoteKey'] ? "['{$keyStr}']" : "[{$keyStr}]") : '[]'; $context = "Property {$className}::\${$propName}" . $formattedKey; + $registry ??= RuntimeTypeChecker::getRegistry(); - return $registry->validate($value, $valueType, $context); + return $registry->validate($value, $contract['valueType'], $context); } } } catch (\Throwable) { @@ -304,6 +398,52 @@ private static function validatePropertyElementMutation( return null; } + /** + * @return ?array{ + * rawType: TypeNode, + * classTemplates: array, + * usesTemplates: bool, + * isNativeNonNullArray: bool, + * isMagicOrMissing: bool + * } + */ + private static function getPropertyMutationPlan(string $className, string $propName): ?array + { + if (isset(self::$propertyMutationPlanCache[$className]) && \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) { + return self::$propertyMutationPlanCache[$className][$propName]; + } + + $rawTypeNode = DocblockParser::parseProperty($className, $propName); + if ($rawTypeNode === null) { + InlineChecker::$nullPropertyCache[$className][$propName] = true; + + return self::$propertyMutationPlanCache[$className][$propName] = null; + } + + $classTemplates = DocblockParser::parseClassTemplates($className); + $usesTemplates = $classTemplates !== [] && DocblockParser::typeReferencesTemplate($rawTypeNode, $classTemplates); + + $isMagicOrMissing = ! property_exists($className, $propName); + $isNativeNonNullArray = false; + if (! $isMagicOrMissing) { + $refProp = self::getReflectionProperty($className, $propName); + if ($refProp !== null && ! $refProp->isStatic()) { + $refType = $refProp->getType(); + $isNativeNonNullArray = $refType instanceof ReflectionNamedType + && $refType->getName() === 'array' + && ! $refType->allowsNull(); + } + } + + return self::$propertyMutationPlanCache[$className][$propName] = [ + 'rawType' => $rawTypeNode, + 'classTemplates' => $classTemplates, + 'usesTemplates' => $usesTemplates, + 'isNativeNonNullArray' => $isNativeNonNullArray, + 'isMagicOrMissing' => $isMagicOrMissing, + ]; + } + /** * Resolves and memoizes the substituted key/value element contract for a property mutation. * @@ -312,121 +452,257 @@ private static function validatePropertyElementMutation( * quoteKey: bool, * keyType: ?TypeNode, * valueType: ?TypeNode, - * keyIsMixed: bool, - * keyIsArrayKey: bool, - * valueIsMixed: bool + * keyOp: int, + * keyExtra: mixed, + * valOp: int, + * valExtra: mixed * } */ private static function resolveElementContract(mixed $objectOrClass, string $className, string $propName): ?array { - if (! isset(self::$propertyMutationPlanCache[$className]) || ! \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) { - $rawTypeNode = DocblockParser::parseProperty($className, $propName); - if ($rawTypeNode === null) { - InlineChecker::$nullPropertyCache[$className][$propName] = true; - self::$propertyMutationPlanCache[$className][$propName] = null; - - return null; - } - - $classTemplates = DocblockParser::parseClassTemplates($className); - $usesTemplates = $classTemplates !== [] && DocblockParser::typeReferencesTemplate($rawTypeNode, $classTemplates); - - self::$propertyMutationPlanCache[$className][$propName] = [ - 'rawType' => $rawTypeNode, - 'classTemplates' => $classTemplates, - 'usesTemplates' => $usesTemplates, - ]; - } - - $propPlan = self::$propertyMutationPlanCache[$className][$propName]; + $propPlan = self::getPropertyMutationPlan($className, $propName); if ($propPlan === null) { return null; } - $sig = ''; + return self::resolveElementContractFromPlan($objectOrClass, $className, $propName, $propPlan); + } + + /** + * @param array{ + * rawType: TypeNode, + * classTemplates: array, + * usesTemplates: bool, + * isNativeNonNullArray: bool, + * isMagicOrMissing: bool + * } $propPlan + * + * @return ?array{ + * isList: bool, + * quoteKey: bool, + * keyType: ?TypeNode, + * valueType: ?TypeNode, + * keyOp: int, + * keyExtra: mixed, + * valOp: int, + * valExtra: mixed + * } + */ + private static function resolveElementContractFromPlan(mixed $objectOrClass, string $className, string $propName, array $propPlan): ?array + { $boundTemplates = []; - if ($propPlan['usesTemplates'] && \is_object($objectOrClass)) { - $boundTemplates = TemplateManager::getBoundTemplatesForInstance($objectOrClass); - if ($boundTemplates !== []) { - foreach ($boundTemplates as $k => $v) { - $sig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; - } + $useInstanceCache = $propPlan['usesTemplates'] && \is_object($objectOrClass); + + if ($useInstanceCache) { + $boundTemplates = TemplateManager::getInstanceBindingsFast($objectOrClass); + self::$instanceContractCache ??= new WeakMap(); + $entry = self::$instanceContractCache[$objectOrClass] ?? null; + + if ( + $entry !== null + && $entry['rawBindings'] === $boundTemplates + && \array_key_exists($propName, $entry['contracts']) + ) { + return $entry['contracts'][$propName]; + } + } + + $sig = ''; + if ($boundTemplates !== []) { + foreach ($boundTemplates as $k => $v) { + $sig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; } } if (isset(self::$substitutedElementContractCache[$className][$propName]) && \array_key_exists($sig, self::$substitutedElementContractCache[$className][$propName])) { - return self::$substitutedElementContractCache[$className][$propName][$sig]; + $contract = self::$substitutedElementContractCache[$className][$propName][$sig]; + } else { + $typeNode = $propPlan['rawType']; + if ($sig !== '') { + $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $propPlan['classTemplates']); + } + + $contract = self::buildElementContract($typeNode); + self::$substitutedElementContractCache[$className][$propName][$sig] = $contract; } - $typeNode = $propPlan['rawType']; - if ($sig !== '') { - $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $propPlan['classTemplates']); + if ($useInstanceCache) { + $entry = self::$instanceContractCache[$objectOrClass] ?? null; + if ($entry === null || $entry['rawBindings'] !== $boundTemplates) { + self::$instanceContractCache[$objectOrClass] = [ + 'rawBindings' => $boundTemplates, + 'contracts' => [$propName => $contract], + ]; + } else { + $entry['contracts'][$propName] = $contract; + self::$instanceContractCache[$objectOrClass] = $entry; + } } - $contract = null; + return $contract; + } + /** + * @return ?array{ + * isList: bool, + * quoteKey: bool, + * keyType: ?TypeNode, + * valueType: ?TypeNode, + * keyOp: int, + * keyExtra: mixed, + * valOp: int, + * valExtra: mixed + * } + */ + private static function buildElementContract(TypeNode $typeNode): ?array + { if ($typeNode instanceof GenericTypeNode) { $base = strtolower((string) $typeNode->type); if ($base === 'list' || $base === 'non-empty-list') { $valueType = $typeNode->genericTypes[0] ?? null; - $contract = [ + [$valOp, $valExtra] = self::compileCheckOp($valueType); + + return [ 'isList' => true, 'quoteKey' => false, 'keyType' => null, 'valueType' => $valueType, - 'keyIsMixed' => false, - 'keyIsArrayKey' => false, - 'valueIsMixed' => $valueType instanceof IdentifierTypeNode && strtolower($valueType->name) === 'mixed', + 'keyOp' => self::OP_NONE, + 'keyExtra' => null, + 'valOp' => $valOp, + 'valExtra' => $valExtra, ]; - } else { + } + + if ($base === 'array' || $base === 'non-empty-array' || $base === 'iterable') { $genericCount = \count($typeNode->genericTypes); $keyType = $genericCount >= 2 ? $typeNode->genericTypes[0] : null; $valueType = $genericCount >= 2 ? $typeNode->genericTypes[1] : ($typeNode->genericTypes[0] ?? null); - $contract = [ + [$keyOp, $keyExtra] = self::compileCheckOp($keyType); + [$valOp, $valExtra] = self::compileCheckOp($valueType); + + return [ 'isList' => false, 'quoteKey' => true, 'keyType' => $keyType, 'valueType' => $valueType, - 'keyIsMixed' => $keyType instanceof IdentifierTypeNode && strtolower($keyType->name) === 'mixed', - 'keyIsArrayKey' => self::isArrayKeyType($keyType), - 'valueIsMixed' => $valueType instanceof IdentifierTypeNode && strtolower($valueType->name) === 'mixed', + 'keyOp' => $keyOp, + 'keyExtra' => $keyExtra, + 'valOp' => $valOp, + 'valExtra' => $valExtra, ]; } - } elseif ($typeNode instanceof ArrayTypeNode) { + + return null; + } + + if ($typeNode instanceof ArrayTypeNode) { $valueType = $typeNode->type; - $contract = [ + [$valOp, $valExtra] = self::compileCheckOp($valueType); + + return [ 'isList' => false, 'quoteKey' => false, 'keyType' => null, 'valueType' => $valueType, - 'keyIsMixed' => false, - 'keyIsArrayKey' => false, - 'valueIsMixed' => $valueType instanceof IdentifierTypeNode && strtolower($valueType->name) === 'mixed', + 'keyOp' => self::OP_NONE, + 'keyExtra' => null, + 'valOp' => $valOp, + 'valExtra' => $valExtra, ]; } - return self::$substitutedElementContractCache[$className][$propName][$sig] = $contract; + return null; } - private static function isArrayKeyType(?TypeNode $node): bool + /** + * @return array{0: int, 1: mixed} + */ + private static function compileCheckOp(?TypeNode $typeNode): array { - if ($node instanceof IdentifierTypeNode) { - return strtolower($node->name) === 'array-key'; + if ($typeNode === null) { + return [self::OP_NONE, null]; } - if ($node instanceof UnionTypeNode && \count($node->types) === 2) { - $t0 = $node->types[0]; - $t1 = $node->types[1]; - if ($t0 instanceof IdentifierTypeNode && $t1 instanceof IdentifierTypeNode) { - $n0 = strtolower($t0->name); - $n1 = strtolower($t1->name); + if ($typeNode instanceof IdentifierTypeNode) { + $name = $typeNode->name; + $lower = strtolower($name); + + return match ($lower) { + 'mixed' => [self::OP_NONE, null], + 'int', 'integer' => [self::OP_INT, null], + 'string' => [self::OP_STRING, null], + 'bool', 'boolean' => [self::OP_BOOL, null], + 'float', 'double' => [self::OP_FLOAT, null], + 'positive-int' => [self::OP_POSITIVE_INT, null], + 'non-empty-string' => [self::OP_NON_EMPTY_STRING, null], + 'array-key' => [self::OP_ARRAY_KEY, null], + 'array' => [self::OP_ARRAY, null], + 'object' => [self::OP_OBJECT, null], + default => (ClassNameValidator::isValid($name) && (class_exists($name, false) || interface_exists($name, false))) + ? [self::OP_CLASS, $name] + : [self::OP_FALLBACK, null], + }; + } + + if ($typeNode instanceof UnionTypeNode) { + $mask = 0; + foreach ($typeNode->types as $member) { + if (! ($member instanceof IdentifierTypeNode)) { + return [self::OP_FALLBACK, null]; + } + + $bit = match (strtolower($member->name)) { + 'int', 'integer' => self::BIT_INT, + 'string' => self::BIT_STRING, + 'bool', 'boolean' => self::BIT_BOOL, + 'float', 'double' => self::BIT_FLOAT, + 'object' => self::BIT_OBJECT, + 'null' => self::BIT_NULL, + 'array' => self::BIT_ARRAY, + 'array-key' => self::BIT_INT | self::BIT_STRING, + default => 0, + }; - return ($n0 === 'int' && $n1 === 'string') || ($n0 === 'string' && $n1 === 'int'); + if ($bit === 0) { + return [self::OP_FALLBACK, null]; + } + + $mask |= $bit; } + + return $mask !== 0 ? [self::OP_MASK, $mask] : [self::OP_FALLBACK, null]; + } + + return [self::OP_FALLBACK, null]; + } + + private static function matchesMask(mixed $value, int $mask): bool + { + if (\is_string($value)) { + return ($mask & self::BIT_STRING) !== 0; + } + if (\is_int($value)) { + return ($mask & (self::BIT_INT | self::BIT_FLOAT)) !== 0; + } + if (\is_object($value)) { + return ($mask & self::BIT_OBJECT) !== 0; + } + if (\is_bool($value)) { + return ($mask & self::BIT_BOOL) !== 0; + } + if (\is_float($value)) { + return ($mask & self::BIT_FLOAT) !== 0; + } + if ($value === null) { + return ($mask & self::BIT_NULL) !== 0; + } + if (\is_array($value)) { + return ($mask & self::BIT_ARRAY) !== 0; } return false; diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index a14c2c30..732f175a 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -974,6 +974,43 @@ public static function getInstanceBoundTypeFast(object $instance, string $templa return self::$instanceTemplateBindings[$instance][$templateName] ?? null; } + /** + * Fast O(1) retrieval of an instance's bound templates, resolving inherited bindings and defaults only when needed. + * + * @return array + */ + public static function getInstanceBindingsFast(object $instance): array + { + $bindings = self::$instanceTemplateBindings !== null + ? (self::$instanceTemplateBindings[$instance] ?? null) + : null; + + $className = $instance::class; + + if ($bindings === null) { + if (self::$pendingCloneSource !== null && is_a($instance, self::$pendingCloneSource::class)) { + self::copyInstanceBindings(self::$pendingCloneSource, $instance); + $bindings = self::$instanceTemplateBindings[$instance] ?? []; + } elseif (! isset(self::$noInheritedBindingsClasses[$className])) { + self::resolveInheritedTemplates($instance, $className); + $bindings = self::$instanceTemplateBindings[$instance] ?? []; + } else { + $bindings = []; + } + } + + $defaults = self::classTemplateDefaults($className); + if ($defaults !== []) { + foreach ($defaults as $tName => $default) { + if (! isset($bindings[$tName])) { + $bindings[$tName] = $default; + } + } + } + + return $bindings; + } + /** * Retrieves all declared template variances ('covariant', 'contravariant', or 'invariant') for an object instance. * @@ -1454,7 +1491,7 @@ public static function isUnspecializedDefault(TemplateTagValueNode $templateTag) */ public static function applyClassTemplateDefaults(object $instance, array $classTemplates): void { - if ($classTemplates === []) { + if ($classTemplates === [] || self::classTemplateDefaults($instance::class) === []) { return; } @@ -3038,14 +3075,22 @@ private static function isRealTypeSymbol(string $name): bool return self::$realTypeSymbolCache[$name]; } - return self::$realTypeSymbolCache[$name] = class_exists($name, false) - || class_exists($name) + if ( + class_exists($name, false) || interface_exists($name, false) - || interface_exists($name) || enum_exists($name, false) - || enum_exists($name) || trait_exists($name, false) - || trait_exists($name); + ) { + return self::$realTypeSymbolCache[$name] = true; + } + + if (class_exists($name, true)) { + return self::$realTypeSymbolCache[$name] = true; + } + + return self::$realTypeSymbolCache[$name] = interface_exists($name, false) + || enum_exists($name, false) + || trait_exists($name, false); } /** diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 7f00bf32..b407770d 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -289,12 +289,12 @@ public static function checkPropertyMemberAssign( mixed $value, string $file ): mixed { - $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); - if ($className !== '' && isset(InlineChecker::$nullPropertyCache[$className][$propName])) { + if (! self::$isEnabled || ! self::$inlinePropertiesEnabled) { return $value; } - if (! self::$isEnabled || ! self::$inlinePropertiesEnabled) { + $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); + if ($className !== '' && isset(InlineChecker::$nullPropertyCache[$className][$propName])) { return $value; } @@ -304,7 +304,7 @@ public static function checkPropertyMemberAssign( $chain, $value, $file, - self::getRegistry() + self::$registry ); if ($res instanceof ErrorMessage) { @@ -1080,11 +1080,11 @@ public static function checkSend( $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); - if (CallerBoundaryResolver::shouldBypass($effectiveFunction)) { + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return $sendValue; } - $res = GeneratorChecker::checkSend($function, $sendValue, self::getRegistry(), $thisOrClass, $scopeCleaner); + $res = GeneratorChecker::checkSend($function, $sendValue, self::getRegistry(), $thisOrClass, $scopeCleaner, $effectiveFunction); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { @@ -1113,11 +1113,11 @@ public static function checkGeneratorReturn( $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); - if (CallerBoundaryResolver::shouldBypass($effectiveFunction)) { + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return $value; } - $res = GeneratorChecker::checkReturn($function, $value, self::getRegistry(), $thisOrClass, $scopeCleaner); + $res = GeneratorChecker::checkReturn($function, $value, self::getRegistry(), $thisOrClass, $scopeCleaner, $effectiveFunction); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { @@ -1147,11 +1147,11 @@ public static function checkYield( $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); - if (CallerBoundaryResolver::shouldBypass($effectiveFunction)) { + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return $value; } - $res = GeneratorChecker::checkYield($function, $key, $value, self::getRegistry(), $thisOrClass, $scopeCleaner); + $res = GeneratorChecker::checkYield($function, $key, $value, self::getRegistry(), $thisOrClass, $scopeCleaner, $effectiveFunction); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { From 06f28b054f789d7afed160e8f7d68648a8a47ac6 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 19 Nov 2026 13:34:13 +0800 Subject: [PATCH 10/25] Refactor type substitution and resolution in TemplateSubstitutor and SpecialTypeResolver - Improved type substitution logic to avoid unnecessary object creation when types remain unchanged in TemplateSubstitutor. - Enhanced the resolveWithContext method in SpecialTypeResolver to streamline type resolution with context, reducing redundancy. - Introduced caching mechanisms in CallableWrapper to optimize callable parameter type resolution and reduce repeated parsing. - Simplified the execution of simple scope plans in RuntimeTypeChecker for better performance and readability. - Added reset functionality for CallableWrapper to clear caches effectively. --- src/Internal/Checker/InlineChecker.php | 57 +++- src/Internal/Checker/MemberAssignChecker.php | 167 ++++++----- src/Internal/Checker/ParamChecker.php | 8 +- src/Internal/Docblock/DocblockParser.php | 41 ++- src/Internal/Generics/TemplateManager.php | 272 ++++++++++++++---- src/Internal/Generics/TemplateSubstitutor.php | 45 ++- src/Internal/Resolver/SpecialTypeResolver.php | 97 +++++-- src/Internal/RuntimeTypeChecker.php | 272 ++++++++++-------- src/Internal/Wrapper/CallableWrapper.php | 141 +++++++-- 9 files changed, 767 insertions(+), 333 deletions(-) diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 92c27043..9172edf4 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -86,6 +86,13 @@ final class InlineChecker */ private static array $resolvedStaticPropertyTypeCache = []; + /** + * In-memory cache for resolved instance property generic types: [$className][$propName] => TypeNode. + * + * @var \WeakMap> + */ + private static ?\WeakMap $instancePropertyTypeCache = null; + /** * Resets internal type node and function caches. Useful for test isolation. */ @@ -703,7 +710,14 @@ private static function resolveClassContext( ?string $methodName, ?object $thisObj ): TypeNode { - if (! class_exists($className) && ! interface_exists($className) && ! trait_exists($className)) { + if ( + ! class_exists($className, false) + && ! interface_exists($className, false) + && ! trait_exists($className, false) + && ! class_exists($className) + && ! interface_exists($className) + && ! trait_exists($className) + ) { return $typeNode; } @@ -763,8 +777,18 @@ private static function resolveClassContext( /** * Substitutes generic template types declared on class properties. */ - private static function substitutePropertyGenerics(TypeNode $typeNode, object $object, string $className): TypeNode + private static function substitutePropertyGenerics(TypeNode $typeNode, object $object, string $className, string $propName = ''): TypeNode { + $boundTemplates = TemplateManager::getInstanceBindingsFast($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]; + } + } + $allTemplates = DocblockParser::parseClassTemplates($className); if ($allTemplates === []) { @@ -773,20 +797,33 @@ private static function substitutePropertyGenerics(TypeNode $typeNode, object $o $allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; } - $boundTemplates = TemplateManager::getBoundTemplates('none', $object, $allTemplates); - $declaredTemplates = $allTemplates; + if ($boundTemplates !== [] || $allTemplates !== []) { + $subNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $allTemplates); - if (\count($boundTemplates) > 0 || \count($declaredTemplates) > 0) { - $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $declaredTemplates); - - if (class_exists($className) || interface_exists($className) || trait_exists($className)) { + if ($subNode !== $typeNode && (class_exists($className, false) || interface_exists($className, false) || trait_exists($className, false) || class_exists($className))) { try { /** @var class-string $className */ $refClass = new \ReflectionClass($className); - $typeNode = SpecialTypeResolver::resolve($typeNode, $refClass); + $typeNode = SpecialTypeResolver::resolve($subNode, $refClass); } catch (\ReflectionException $e) { - // Silently continue if reflection fails + $typeNode = $subNode; } + } else { + $typeNode = $subNode; + } + } + + if ($propName !== '') { + self::$instancePropertyTypeCache ??= new \WeakMap(); + $entry = self::$instancePropertyTypeCache[$object] ?? null; + if ($entry === null || $entry['bindings'] !== $boundTemplates) { + self::$instancePropertyTypeCache[$object] = [ + 'bindings' => $boundTemplates, + 'props' => [$propName => $typeNode], + ]; + } else { + $entry['props'][$propName] = $typeNode; + self::$instancePropertyTypeCache[$object] = $entry; } } diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 72159a8b..1c59f2d6 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -30,41 +30,25 @@ final class MemberAssignChecker { private const OP_NONE = 0; - private const OP_INT = 1; - private const OP_STRING = 2; - private const OP_BOOL = 3; - private const OP_FLOAT = 4; private const OP_POSITIVE_INT = 5; - private const OP_NON_EMPTY_STRING = 6; private const OP_ARRAY_KEY = 7; - private const OP_ARRAY = 8; - private const OP_OBJECT = 9; - private const OP_CLASS = 10; - private const OP_MASK = 11; - private const OP_FALLBACK = 12; private const BIT_INT = 1; - private const BIT_STRING = 2; - private const BIT_BOOL = 4; - private const BIT_FLOAT = 8; - private const BIT_OBJECT = 16; - private const BIT_NULL = 32; - private const BIT_ARRAY = 64; /** @@ -231,7 +215,10 @@ public static function checkProperty( } if (\count($chain) === 1 && $chain[0][0] === 'dim') { - $propPlan = self::getPropertyMutationPlan($className, $propName); + $propPlan = (isset(self::$propertyMutationPlanCache[$className]) && \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) + ? self::$propertyMutationPlanCache[$className][$propName] + : self::buildPropertyMutationPlan($className, $propName); + if ($propPlan === null) { return $value; } @@ -242,22 +229,42 @@ public static function checkProperty( && $propPlan['isNativeNonNullArray'] && \is_object($objectOrClass) ) { - $contract = self::resolveElementContractFromPlan($objectOrClass, $className, $propName, $propPlan); - if ($contract !== null && (! $contract['isList'] || $chain[0][1] === null)) { + $contract = null; + + if ($propPlan['usesTemplates']) { + $boundTemplates = TemplateManager::getInstanceBindingsFast($objectOrClass); + self::$instanceContractCache ??= new WeakMap(); + $entry = self::$instanceContractCache[$objectOrClass] ?? null; + + if ( + $entry !== null + && $entry['rawBindings'] === $boundTemplates + && \array_key_exists($propName, $entry['contracts']) + ) { + $contract = $entry['contracts'][$propName]; + } else { + $contract = self::resolveElementContractFromPlan($objectOrClass, $className, $propName, $propPlan, $boundTemplates); + } + } elseif (isset(self::$substitutedElementContractCache[$className][$propName]) && \array_key_exists('', self::$substitutedElementContractCache[$className][$propName])) { + $contract = self::$substitutedElementContractCache[$className][$propName]['']; + } else { + $contract = self::resolveElementContractFromPlan($objectOrClass, $className, $propName, $propPlan); + } + + $key = $chain[0][1]; + if ($contract !== null && (! $contract['isList'] || $key === null)) { $directErr = self::validatePropertyElementMutationWithContract( $className, $propName, - $chain[0][1], + $key, $value, $contract, $registry ); - if ($directErr instanceof ErrorMessage) { - return $directErr; + if ($directErr === null) { + return $value; } - - return $value; } } } @@ -343,14 +350,22 @@ private static function validatePropertyElementMutationWithContract( return ErrorFactory::createError("Property {$className}::\${$propName} must be a list, non-integer key '{$keyStr}' given"); } } elseif ($key !== null && $contract['keyOp'] !== self::OP_NONE) { + $keyOp = $contract['keyOp']; $keyExtra = $contract['keyExtra']; - $keyOk = match ($contract['keyOp']) { + $keyOk = match ($keyOp) { self::OP_INT => \is_int($key), self::OP_STRING => \is_string($key), self::OP_ARRAY_KEY => \is_int($key) || \is_string($key), self::OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', self::OP_POSITIVE_INT => \is_int($key) && $key > 0, - self::OP_MASK => self::matchesMask($key, (int) $keyExtra), + self::OP_MASK => ( + (\is_string($key) && (((int) $keyExtra) & self::BIT_STRING) !== 0) + || (\is_int($key) && (((int) $keyExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($key) && (((int) $keyExtra) & self::BIT_OBJECT) !== 0) + || (\is_bool($key) && (((int) $keyExtra) & self::BIT_BOOL) !== 0) + || (\is_float($key) && (((int) $keyExtra) & self::BIT_FLOAT) !== 0) + || (\is_array($key) && (((int) $keyExtra) & self::BIT_ARRAY) !== 0) + ), self::OP_OBJECT => \is_object($key), self::OP_CLASS => \is_object($key) && ($key instanceof $keyExtra), default => false, @@ -379,7 +394,15 @@ private static function validatePropertyElementMutationWithContract( self::OP_ARRAY => \is_array($value), self::OP_OBJECT => \is_object($value), self::OP_CLASS => \is_object($value) && ($value instanceof $valExtra), - self::OP_MASK => self::matchesMask($value, (int) $valExtra), + self::OP_MASK => ( + (\is_string($value) && (((int) $valExtra) & self::BIT_STRING) !== 0) + || (\is_int($value) && (((int) $valExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($value) && (((int) $valExtra) & self::BIT_OBJECT) !== 0) + || (\is_bool($value) && (((int) $valExtra) & self::BIT_BOOL) !== 0) + || (\is_float($value) && (((int) $valExtra) & self::BIT_FLOAT) !== 0) + || ($value === null && (((int) $valExtra) & self::BIT_NULL) !== 0) + || (\is_array($value) && (((int) $valExtra) & self::BIT_ARRAY) !== 0) + ), default => false, }; @@ -407,12 +430,8 @@ private static function validatePropertyElementMutationWithContract( * isMagicOrMissing: bool * } */ - private static function getPropertyMutationPlan(string $className, string $propName): ?array + private static function buildPropertyMutationPlan(string $className, string $propName): ?array { - if (isset(self::$propertyMutationPlanCache[$className]) && \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) { - return self::$propertyMutationPlanCache[$className][$propName]; - } - $rawTypeNode = DocblockParser::parseProperty($className, $propName); if ($rawTypeNode === null) { InlineChecker::$nullPropertyCache[$className][$propName] = true; @@ -460,7 +479,10 @@ private static function getPropertyMutationPlan(string $className, string $propN */ private static function resolveElementContract(mixed $objectOrClass, string $className, string $propName): ?array { - $propPlan = self::getPropertyMutationPlan($className, $propName); + $propPlan = (isset(self::$propertyMutationPlanCache[$className]) && \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) + ? self::$propertyMutationPlanCache[$className][$propName] + : self::buildPropertyMutationPlan($className, $propName); + if ($propPlan === null) { return null; } @@ -476,6 +498,7 @@ private static function resolveElementContract(mixed $objectOrClass, string $cla * isNativeNonNullArray: bool, * isMagicOrMissing: bool * } $propPlan + * @param array|null $preFetchedBindings * * @return ?array{ * isList: bool, @@ -488,13 +511,18 @@ private static function resolveElementContract(mixed $objectOrClass, string $cla * valExtra: mixed * } */ - private static function resolveElementContractFromPlan(mixed $objectOrClass, string $className, string $propName, array $propPlan): ?array - { + private static function resolveElementContractFromPlan( + mixed $objectOrClass, + string $className, + string $propName, + array $propPlan, + ?array $preFetchedBindings = null + ): ?array { $boundTemplates = []; $useInstanceCache = $propPlan['usesTemplates'] && \is_object($objectOrClass); if ($useInstanceCache) { - $boundTemplates = TemplateManager::getInstanceBindingsFast($objectOrClass); + $boundTemplates = $preFetchedBindings ?? TemplateManager::getInstanceBindingsFast($objectOrClass); self::$instanceContractCache ??= new WeakMap(); $entry = self::$instanceContractCache[$objectOrClass] ?? null; @@ -518,7 +546,7 @@ private static function resolveElementContractFromPlan(mixed $objectOrClass, str $contract = self::$substitutedElementContractCache[$className][$propName][$sig]; } else { $typeNode = $propPlan['rawType']; - if ($sig !== '') { + if ($propPlan['usesTemplates']) { $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $propPlan['classTemplates']); } @@ -575,29 +603,25 @@ private static function buildElementContract(TypeNode $typeNode): ?array ]; } - if ($base === 'array' || $base === 'non-empty-array' || $base === 'iterable') { - $genericCount = \count($typeNode->genericTypes); - $keyType = $genericCount >= 2 ? $typeNode->genericTypes[0] : null; - $valueType = $genericCount >= 2 - ? $typeNode->genericTypes[1] - : ($typeNode->genericTypes[0] ?? null); + $genericCount = \count($typeNode->genericTypes); + $keyType = $genericCount >= 2 ? $typeNode->genericTypes[0] : null; + $valueType = $genericCount >= 2 + ? $typeNode->genericTypes[1] + : ($typeNode->genericTypes[0] ?? null); - [$keyOp, $keyExtra] = self::compileCheckOp($keyType); - [$valOp, $valExtra] = self::compileCheckOp($valueType); - - return [ - 'isList' => false, - 'quoteKey' => true, - 'keyType' => $keyType, - 'valueType' => $valueType, - 'keyOp' => $keyOp, - 'keyExtra' => $keyExtra, - 'valOp' => $valOp, - 'valExtra' => $valExtra, - ]; - } + [$keyOp, $keyExtra] = self::compileCheckOp($keyType); + [$valOp, $valExtra] = self::compileCheckOp($valueType); - return null; + return [ + 'isList' => false, + 'quoteKey' => true, + 'keyType' => $keyType, + 'valueType' => $valueType, + 'keyOp' => $keyOp, + 'keyExtra' => $keyExtra, + 'valOp' => $valOp, + 'valExtra' => $valExtra, + ]; } if ($typeNode instanceof ArrayTypeNode) { @@ -681,33 +705,6 @@ private static function compileCheckOp(?TypeNode $typeNode): array return [self::OP_FALLBACK, null]; } - private static function matchesMask(mixed $value, int $mask): bool - { - if (\is_string($value)) { - return ($mask & self::BIT_STRING) !== 0; - } - if (\is_int($value)) { - return ($mask & (self::BIT_INT | self::BIT_FLOAT)) !== 0; - } - if (\is_object($value)) { - return ($mask & self::BIT_OBJECT) !== 0; - } - if (\is_bool($value)) { - return ($mask & self::BIT_BOOL) !== 0; - } - if (\is_float($value)) { - return ($mask & self::BIT_FLOAT) !== 0; - } - if ($value === null) { - return ($mask & self::BIT_NULL) !== 0; - } - if (\is_array($value)) { - return ($mask & self::BIT_ARRAY) !== 0; - } - - return false; - } - /** * Safely reads the current value of an instance or static property across all visibilities. */ diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index ddedf682..e0992f4d 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -270,7 +270,7 @@ public static function checkParams( /** @var array $allTemplates */ $allTemplates = [...$classTemplates, ...$methodTemplates]; - if (\count($allTemplates) > 0 && $paramsUseGenerics) { + if (\count($allTemplates) > 0 && $paramsUseGenerics && ($contract['paramsNeedPreInference'] ?? true)) { self::preInferGenericTemplates($contract['types'], $vars, $effectiveFunction, $thisObj, $allTemplates, $classTemplates); } @@ -2028,8 +2028,10 @@ private static function validateSingleParam( $shouldSkipTemplateSub = $isBareTemplate || $isClassStringT; if (! $shouldSkipTemplateSub && (\count($boundTemplates) > 0 || \count($declaredTemplates) > 0)) { - $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $declaredTemplates); - $typeNode = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); + $subType = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $declaredTemplates); + if ($subType !== $typeNode) { + $typeNode = SpecialTypeResolver::resolve($subType, $effectiveFunction, $thisObj); + } } if (ConditionalChecker::containsConditional($typeNode)) { diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index bd63e5b4..25784c22 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -299,11 +299,10 @@ private static function isUnconstrainedType(TypeNode $typeNode): bool } /** - * Computes pre-optimized flags for a contract to avoid redundant re-parsing. - * * @param array $types * @param array $aliases * @param array $methodTemplates + * @param array $allTemplates * * @return array{ * constrainedTypes: array, @@ -311,7 +310,10 @@ private static function isUnconstrainedType(TypeNode $typeNode): bool * allParamsUnconstrained: bool, * returnUnconstrained: bool, * returnHasConditional: bool, - * isSimple: bool + * isSimple: bool, + * paramsAreSimple: bool, + * hasCrossReferencedBounds: bool, + * paramsNeedPreInference: bool * } */ private static function computeContractFlags( @@ -321,10 +323,12 @@ private static function computeContractFlags( bool $returnUsesGenerics, array $aliases, array $methodTemplates, - bool $paramsAreDynamic = false + bool $paramsAreDynamic = false, + array $allTemplates = [] ): array { $constrainedTypes = []; $paramConditionals = []; + $paramsNeedPreInference = false; foreach ($types as $paramName => $tNode) { if (! ($tNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($tNode)) { @@ -333,6 +337,16 @@ private static function computeContractFlags( } elseif (! self::isUnconstrainedType($tNode)) { $constrainedTypes[$paramName] = $tNode; } + + if (! $paramsNeedPreInference) { + $inner = $tNode; + while ($inner instanceof NullableTypeNode) { + $inner = $inner->type; + } + if (! ($inner instanceof IdentifierTypeNode)) { + $paramsNeedPreInference = true; + } + } } $allParamsUnconstrained = ($constrainedTypes === []); @@ -346,12 +360,24 @@ private static function computeContractFlags( $returnHasConditional = ConditionalChecker::containsConditional($returnType); } - $isSimple = ! $paramsUseGenerics + $paramsAreSimple = ! $paramsUseGenerics && ! $paramsAreDynamic - && ! $returnUsesGenerics && \count($aliases) === 0 && \count($methodTemplates) === 0; + $isSimple = $paramsAreSimple && ! $returnUsesGenerics; + + $hasCrossReferencedBounds = false; + if ($allTemplates !== []) { + foreach ($allTemplates as $templateNode) { + if ($templateNode->bound !== null && self::typeReferencesTemplate($templateNode->bound, $allTemplates)) { + $hasCrossReferencedBounds = true; + + break; + } + } + } + return [ 'constrainedTypes' => $constrainedTypes, 'paramConditionals' => $paramConditionals, @@ -359,6 +385,9 @@ private static function computeContractFlags( 'returnUnconstrained' => $returnUnconstrained, 'returnHasConditional' => $returnHasConditional, 'isSimple' => $isSimple, + 'paramsAreSimple' => $paramsAreSimple, + 'hasCrossReferencedBounds' => $hasCrossReferencedBounds, + 'paramsNeedPreInference' => $paramsNeedPreInference, ]; } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 732f175a..d5ea29e3 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -539,11 +539,23 @@ final class TemplateManager */ private static array $noInheritedBindingsClasses = []; + /** + * @var WeakMap, propIds: list}>|null + */ + private static ?WeakMap $propagatedBindingsCache = null; + + /** + * @var array, \ReflectionClass> + */ + private static array $refClassCache = []; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ public static function reset(): void { + self::$propagatedBindingsCache = null; + self::$refClassCache = []; self::$instanceTemplateBindings = null; self::$callStackBindings = []; self::$activeCallOrder = []; @@ -1250,7 +1262,6 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t $existingBindings !== null && ! $forceBind && ! $refineOnly - && ! $plan['hasPropagation'] && self::$generatorInferredCallFrames === [] ) { $allFastMatched = true; @@ -1298,6 +1309,10 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t } if ($allFastMatched) { + if ($plan['hasPropagation']) { + self::propagateBindingsIfNeeded($instance, $existingBindings); + } + return null; } } @@ -1343,7 +1358,8 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t } if ($plan['hasPropagation']) { - self::propagateBindingsToInstanceProperties($instance); + $currentBindings = self::$instanceTemplateBindings[$instance] ?? []; + self::propagateBindingsIfNeeded($instance, $currentBindings); } return null; @@ -1546,21 +1562,77 @@ private static function propagationPlan(string $className): array } /** - * Propagates resolved class template bindings on an instance to any of its object properties - * whose declared types reference those class templates (e.g. $this->store with @var KeyValueStore). + * @param array $instanceBindings */ - private static function propagateBindingsToInstanceProperties(object $instance): void + private static function propagateBindingsIfNeeded(object $instance, array $instanceBindings): void { - if (self::$instanceTemplateBindings === null || ! isset(self::$instanceTemplateBindings[$instance])) { + if ($instanceBindings === []) { return; } - $instanceBindings = self::$instanceTemplateBindings[$instance]; + $plan = self::propagationPlan($instance::class); + if ($plan === []) { + return; + } + + if (\PHP_VERSION_ID >= 80400) { + $className = $instance::class; + $refClass = self::$refClassCache[$className] ??= new \ReflectionClass($className); + if ($refClass->isUninitializedLazyObject($instance)) { + return; + } + } + + self::$propagatedBindingsCache ??= new WeakMap(); + $cached = self::$propagatedBindingsCache[$instance] ?? null; + + if ($cached !== null && $cached['bindings'] === $instanceBindings) { + $allSameProps = true; + foreach ($plan as $idx => $entry) { + $prop = $entry['prop']; + if ((\PHP_VERSION_ID >= 80400 && $prop->isLazy($instance)) || ! $prop->isInitialized($instance)) { + $propId = -1; + } else { + $val = $prop->getValue($instance); + $propId = \is_object($val) ? spl_object_id($val) : 0; + } + + if (($cached['propIds'][$idx] ?? null) !== $propId) { + $allSameProps = false; + + break; + } + } + + if ($allSameProps) { + return; + } + } + + self::propagateBindingsToInstanceProperties($instance, $instanceBindings, $plan); + } + + /** + * @param array|null $instanceBindings + * @param list|null $plan + */ + private static function propagateBindingsToInstanceProperties( + object $instance, + ?array $instanceBindings = null, + ?array $plan = null + ): void { + if ($instanceBindings === null) { + if (self::$instanceTemplateBindings === null || ! isset(self::$instanceTemplateBindings[$instance])) { + return; + } + $instanceBindings = self::$instanceTemplateBindings[$instance]; + } + if ($instanceBindings === []) { return; } - $plan = self::propagationPlan($instance::class); + $plan ??= self::propagationPlan($instance::class); if ($plan === []) { return; } @@ -1571,27 +1643,41 @@ private static function propagateBindingsToInstanceProperties(object $instance): } self::$propagationStack[$oid] = true; + $propIds = []; + try { - if (\PHP_VERSION_ID >= 80400 && (new \ReflectionObject($instance))->isUninitializedLazyObject($instance)) { - return; + if (\PHP_VERSION_ID >= 80400) { + $className = $instance::class; + $refClass = self::$refClassCache[$className] ??= new \ReflectionClass($className); + if ($refClass->isUninitializedLazyObject($instance)) { + return; + } } - foreach ($plan as $entry) { + foreach ($plan as $idx => $entry) { $prop = $entry['prop']; if (\PHP_VERSION_ID >= 80400 && $prop->isLazy($instance)) { + $propIds[$idx] = -1; + continue; } if (! $prop->isInitialized($instance)) { + $propIds[$idx] = -1; + continue; } $propVal = $prop->getValue($instance); if (! \is_object($propVal)) { + $propIds[$idx] = 0; + continue; } + $propIds[$idx] = spl_object_id($propVal); + if (! DocblockParser::typeReferencesTemplate($entry['type'], $instanceBindings)) { continue; } @@ -1601,6 +1687,12 @@ private static function propagateBindingsToInstanceProperties(object $instance): self::bindInstanceFromNode($propVal, $resolvedPropType, forceBind: true, refineOnly: true); } } + + self::$propagatedBindingsCache ??= new WeakMap(); + self::$propagatedBindingsCache[$instance] = [ + 'bindings' => $instanceBindings, + 'propIds' => $propIds, + ]; } catch (\Throwable) { } finally { unset(self::$propagationStack[$oid]); @@ -2477,36 +2569,46 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return false; } - $existingStr = (string) $existing; - $expectedStr = (string) $expected; + if ($variance === GenericTypeNode::VARIANCE_INVARIANT && $existing::class === $expected::class) { + if ((string) $existing === (string) $expected) { + return true; + } + } - if ($existingStr === $expectedStr || $expectedStr === 'mixed' || $expectedStr === '*') { - return true; + if ($expected instanceof UnionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { + return self::checkExpectedUnionVariance($existing, $expected, $variance); } - $lowerExpected = strtolower($expectedStr); - $lowerExisting = strtolower($existingStr); + if ($existing instanceof UnionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { + return self::checkExistingUnionVariance($existing, $expected, $variance); + } - if ($lowerExpected === 'object' && ClassNameValidator::isValid($existingStr) && self::isRealTypeSymbol($existingStr)) { - return true; + if ($expected instanceof IntersectionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { + return self::checkExpectedIntersectionVariance($existing, $expected, $variance); } - if (self::isScalarSubtype($lowerExisting, $lowerExpected)) { - return true; + if ($existing instanceof IntersectionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { + return self::checkExistingIntersectionVariance($existing, $expected, $variance); } - $baseExpected = strtolower($expected instanceof GenericTypeNode ? (string) $expected->type : ($expected instanceof IdentifierTypeNode ? $expected->name : $expectedStr)); - $baseExisting = strtolower($existing instanceof GenericTypeNode ? (string) $existing->type : ($existing instanceof IdentifierTypeNode ? $existing->name : $existingStr)); + if ($existing instanceof ArrayTypeNode && $expected instanceof ArrayTypeNode) { + return self::checkVariance($existing->type, $expected->type, $variance); + } - if ($variance === GenericTypeNode::VARIANCE_COVARIANT && isset(self::COLLECTION_SUBTYPES[$baseExpected])) { - $allowedSubtypes = self::COLLECTION_SUBTYPES[$baseExpected]; + if ($existing instanceof ArrayShapeNode && $expected instanceof ArrayShapeNode) { + return self::checkNestedArrayShapeVariance($existing, $expected, $variance); + } - if (isset($allowedSubtypes[$baseExisting])) { - if ($expected instanceof IdentifierTypeNode) { - return true; - } + if ($existing instanceof GenericTypeNode && $expected instanceof GenericTypeNode) { + if (self::checkNestedGenericVariance($existing, $expected)) { + return true; + } + + if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { + $baseExpected = strtolower((string) $expected->type); + $baseExisting = strtolower((string) $existing->type); - if ($expected instanceof GenericTypeNode) { + if (isset(self::COLLECTION_SUBTYPES[$baseExpected][$baseExisting])) { $allUnconstrained = true; foreach ($expected->genericTypes as $gt) { if (! self::isUnspecializedType($gt)) { @@ -2522,31 +2624,87 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } } - if ($existing instanceof ArrayTypeNode || $existing instanceof ArrayShapeNode) { - if ($baseExpected === 'array' || $baseExpected === 'iterable') { - if ($expected instanceof IdentifierTypeNode) { - return true; - } + return false; + } - if ($expected instanceof GenericTypeNode) { - $allUnconstrained = true; - foreach ($expected->genericTypes as $gt) { - if (! self::isUnspecializedType($gt)) { - $allUnconstrained = false; + if ($existing instanceof IdentifierTypeNode && $expected instanceof GenericTypeNode) { + if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { + $baseExpected = strtolower((string) $expected->type); + $baseExisting = strtolower($existing->name); + if (isset(self::COLLECTION_SUBTYPES[$baseExpected][$baseExisting])) { + $allUnconstrained = true; + foreach ($expected->genericTypes as $gt) { + if (! self::isUnspecializedType($gt)) { + $allUnconstrained = false; - break; - } + break; } + } - if ($allUnconstrained) { - return true; - } + if ($allUnconstrained) { + return true; } } } - if ($existing instanceof GenericTypeNode && isset($allowedSubtypes[$baseExisting])) { - if ($expected instanceof IdentifierTypeNode) { + return self::checkIdentifierAgainstGenericVariance($existing, $expected, $variance); + } + + if ($expected instanceof IdentifierTypeNode) { + $lowerExpected = strtolower($expected->name); + + if ($lowerExpected === 'mixed' || $lowerExpected === '*') { + return true; + } + + if ($existing instanceof ArrayTypeNode || $existing instanceof ArrayShapeNode) { + if ($variance === GenericTypeNode::VARIANCE_COVARIANT && ($lowerExpected === 'array' || $lowerExpected === 'iterable')) { + return true; + } + + return false; + } + + if ($existing instanceof GenericTypeNode) { + $baseExisting = strtolower((string) $existing->type); + + if ($variance === GenericTypeNode::VARIANCE_COVARIANT && isset(self::COLLECTION_SUBTYPES[$lowerExpected][$baseExisting])) { + return true; + } + + if (($baseExisting === 'int' || $baseExisting === 'integer') && isset(self::INT_SUPERTYPES[$lowerExpected])) { + return true; + } + + if ($baseExisting === 'class-string' && isset(self::STRING_SUPERTYPES[$lowerExpected])) { + return true; + } + + if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { + return self::isSubclass((string) $existing->type, $expected->name); + } + + if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { + return self::isSubclass($expected->name, (string) $existing->type); + } + + return false; + } + } + + if (($existing instanceof ArrayTypeNode || $existing instanceof ArrayShapeNode) && $expected instanceof GenericTypeNode && $variance === GenericTypeNode::VARIANCE_COVARIANT) { + $baseExpected = strtolower((string) $expected->type); + if ($baseExpected === 'array' || $baseExpected === 'iterable') { + $allUnconstrained = true; + foreach ($expected->genericTypes as $gt) { + if (! self::isUnspecializedType($gt)) { + $allUnconstrained = false; + + break; + } + } + + if ($allUnconstrained) { return true; } } @@ -2568,20 +2726,22 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::checkExistingIntersectionVariance($existing, $expected, $variance); } - if ($existing instanceof ArrayTypeNode && $expected instanceof ArrayTypeNode) { - return self::checkVariance($existing->type, $expected->type, $variance); - } + $existingStr = (string) $existing; + $expectedStr = (string) $expected; - if ($existing instanceof ArrayShapeNode && $expected instanceof ArrayShapeNode) { - return self::checkNestedArrayShapeVariance($existing, $expected, $variance); + if ($existingStr === $expectedStr || $expectedStr === 'mixed' || $expectedStr === '*') { + return true; } - if ($existing instanceof GenericTypeNode && $expected instanceof GenericTypeNode) { - return self::checkNestedGenericVariance($existing, $expected); + $lowerExpected = strtolower($expectedStr); + $lowerExisting = strtolower($existingStr); + + if ($lowerExpected === 'object' && ClassNameValidator::isValid($existingStr) && self::isRealTypeSymbol($existingStr)) { + return true; } - if ($existing instanceof IdentifierTypeNode && $expected instanceof GenericTypeNode) { - return self::checkIdentifierAgainstGenericVariance($existing, $expected, $variance); + if (self::isScalarSubtype($lowerExisting, $lowerExpected)) { + return true; } if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { diff --git a/src/Internal/Generics/TemplateSubstitutor.php b/src/Internal/Generics/TemplateSubstitutor.php index b4ebe7ac..021ed8ba 100644 --- a/src/Internal/Generics/TemplateSubstitutor.php +++ b/src/Internal/Generics/TemplateSubstitutor.php @@ -163,7 +163,9 @@ private static function substituteNode( } if ($node instanceof ArrayTypeNode) { - return new ArrayTypeNode(self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited)); + $inner = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); + + return $inner === $node->type ? $node : new ArrayTypeNode($inner); } if ($node instanceof GenericTypeNode) { @@ -171,25 +173,37 @@ private static function substituteNode( } if ($node instanceof NullableTypeNode) { - return new NullableTypeNode(self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited)); + $inner = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); + + return $inner === $node->type ? $node : new NullableTypeNode($inner); } if ($node instanceof UnionTypeNode) { $types = []; + $changed = false; foreach ($node->types as $t) { - $types[] = self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited); + $sub = self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited); + if ($sub !== $t) { + $changed = true; + } + $types[] = $sub; } - return self::normalizeUnion($types); + return $changed ? self::normalizeUnion($types) : $node; } if ($node instanceof IntersectionTypeNode) { $types = []; + $changed = false; foreach ($node->types as $t) { - $types[] = self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited); + $sub = self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited); + if ($sub !== $t) { + $changed = true; + } + $types[] = $sub; } - return self::normalizeIntersection($types); + return $changed ? self::normalizeIntersection($types) : $node; } if ($node instanceof ArrayShapeNode) { @@ -234,10 +248,10 @@ private static function substituteIdentifier( } /** - * @param array $boundTemplates - * @param array $declaredTemplates - * @param array $visited - */ + * @param array $boundTemplates + * @param array $declaredTemplates + * @param array $visited + */ private static function substituteCallable( CallableTypeNode $node, array $boundTemplates, @@ -327,9 +341,18 @@ private static function substituteGeneric( array $visited ): GenericTypeNode { $type = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); + $changed = ($type !== $node->type); $genericTypes = []; foreach ($node->genericTypes as $gt) { - $genericTypes[] = self::substituteNode($gt, $boundTemplates, $declaredTemplates, $visited); + $sub = self::substituteNode($gt, $boundTemplates, $declaredTemplates, $visited); + if ($sub !== $gt) { + $changed = true; + } + $genericTypes[] = $sub; + } + + if (! $changed) { + return $node; } return new GenericTypeNode( diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index bd8c4074..d93aac22 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -234,7 +234,34 @@ public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunct } $ref = self::getReflectionContext($context); - $declaringClass = $ref instanceof \ReflectionMethod ? $ref->getDeclaringClass()->getName() : ($ref instanceof \ReflectionClass ? $ref->getName() : null); + $declaringClass = $ref instanceof \ReflectionMethod + ? $ref->getDeclaringClass()->getName() + : ($ref instanceof \ReflectionClass ? $ref->getName() : null); + + return self::resolveWithContext($node, $ref, $declaringClass, $context, $thisObj); + } + + /** + * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref + * @param \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context + */ + private static function resolveWithContext( + TypeNode $node, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref, + ?string $declaringClass, + \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, + ?object $thisObj = null + ): TypeNode { + if ($node instanceof IdentifierTypeNode) { + $lower = strtolower($node->name); + if (isset(self::BUILTIN_TYPE_KEYWORDS[$lower]) && $lower !== 'self' && $lower !== 'parent' && $lower !== 'static' && $lower !== '$this') { + if (! isset(self::OVERRIDABLE_SCALAR_ALIASES[$lower]) || $node->name === $lower) { + return $node; + } + } + + return self::resolveIdentifier($node, $declaringClass, $ref, $context, $thisObj); + } if ($node instanceof ThisTypeNode) { if ($thisObj !== null) { @@ -251,19 +278,24 @@ public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunct return $node; } - if ($node instanceof IdentifierTypeNode) { - return self::resolveIdentifier($node, $declaringClass, $ref, $context, $thisObj); - } - if ($node instanceof ConstTypeNode) { return self::resolveConstType($node, $declaringClass, $ref); } if ($node instanceof GenericTypeNode) { - $genericType = self::resolve($node->type, $context, $thisObj); + $genericType = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj); + $changed = ($genericType !== $node->type); $innerTypes = []; foreach ($node->genericTypes as $gt) { - $innerTypes[] = self::resolve($gt, $context, $thisObj); + $resGt = self::resolveWithContext($gt, $ref, $declaringClass, $context, $thisObj); + if ($resGt !== $gt) { + $changed = true; + } + $innerTypes[] = $resGt; + } + + if (! $changed) { + return $node; } return new GenericTypeNode( @@ -291,10 +323,10 @@ public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunct if ($node instanceof ConditionalTypeNode) { return new ConditionalTypeNode( - self::resolve($node->subjectType, $context, $thisObj), - self::resolve($node->targetType, $context, $thisObj), - self::resolve($node->if, $context, $thisObj), - self::resolve($node->else, $context, $thisObj), + self::resolveWithContext($node->subjectType, $ref, $declaringClass, $context, $thisObj), + self::resolveWithContext($node->targetType, $ref, $declaringClass, $context, $thisObj), + self::resolveWithContext($node->if, $ref, $declaringClass, $context, $thisObj), + self::resolveWithContext($node->else, $ref, $declaringClass, $context, $thisObj), $node->negated ); } @@ -302,37 +334,51 @@ public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunct if ($node instanceof ConditionalTypeForParameterNode) { return new ConditionalTypeForParameterNode( $node->parameterName, - self::resolve($node->targetType, $context, $thisObj), - self::resolve($node->if, $context, $thisObj), - self::resolve($node->else, $context, $thisObj), + self::resolveWithContext($node->targetType, $ref, $declaringClass, $context, $thisObj), + self::resolveWithContext($node->if, $ref, $declaringClass, $context, $thisObj), + self::resolveWithContext($node->else, $ref, $declaringClass, $context, $thisObj), $node->negated ); } if ($node instanceof NullableTypeNode) { - return new NullableTypeNode(self::resolve($node->type, $context, $thisObj)); + $resInner = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj); + + return $resInner === $node->type ? $node : new NullableTypeNode($resInner); } if ($node instanceof ArrayTypeNode) { - return new ArrayTypeNode(self::resolve($node->type, $context, $thisObj)); + $resInner = self::resolveWithContext($node->type, $ref, $declaringClass, $context, $thisObj); + + return $resInner === $node->type ? $node : new ArrayTypeNode($resInner); } if ($node instanceof UnionTypeNode) { $types = []; + $changed = false; foreach ($node->types as $t) { - $types[] = self::resolve($t, $context, $thisObj); + $resT = self::resolveWithContext($t, $ref, $declaringClass, $context, $thisObj); + if ($resT !== $t) { + $changed = true; + } + $types[] = $resT; } - return new UnionTypeNode($types); + return $changed ? new UnionTypeNode($types) : $node; } if ($node instanceof IntersectionTypeNode) { $types = []; + $changed = false; foreach ($node->types as $t) { - $types[] = self::resolve($t, $context, $thisObj); + $resT = self::resolveWithContext($t, $ref, $declaringClass, $context, $thisObj); + if ($resT !== $t) { + $changed = true; + } + $types[] = $resT; } - return new IntersectionTypeNode($types); + return $changed ? new IntersectionTypeNode($types) : $node; } return $node; @@ -1416,10 +1462,13 @@ class_exists($symbol, false) return false; } - return class_exists($symbol) - || interface_exists($symbol) - || enum_exists($symbol) - || trait_exists($symbol); + if (class_exists($symbol, true)) { + return true; + } + + return interface_exists($symbol, false) + || enum_exists($symbol, false) + || trait_exists($symbol, false); } /** diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index b407770d..cd7db747 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -135,6 +135,7 @@ public static function reset(): void SelfOutChecker::reset(); GeneratorChecker::reset(); ViolationCollector::reset(); + CallableWrapper::reset(); } /** @@ -525,74 +526,27 @@ public static function setupScope(string $function, array $vars, object|string|n $plan = self::$simpleScopePlanCache[$function] ?? null; - // Fast-path: pre-compiled simple non-templated scope plan with direct class match - if ($plan !== null && ($thisOrClass === null || (\is_object($thisOrClass) ? $thisOrClass::class === $plan['class'] : $thisOrClass === $plan['class']))) { - if ($vars === []) { - return null; - } - - $registry = self::$registry ??= new TypeValidatorRegistry(); - $effectiveFunc = $plan['function']; - - foreach ($plan['items'] as $item) { - $paramName = $item[0]; - - if (isset($vars[$paramName])) { - $val = $vars[$paramName]; - } elseif (\array_key_exists($paramName, $vars)) { - $val = null; - } else { - continue; - } - - $ok = match ($item[1]) { - self::PARAM_CHECK_POSITIVE_INT => \is_int($val) && $val > 0, - self::PARAM_CHECK_NON_EMPTY_STRING => \is_string($val) && $val !== '', - self::PARAM_CHECK_INT => \is_int($val), - 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_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)), - self::PARAM_CHECK_NON_NEGATIVE_INT => \is_int($val) && $val >= 0, - self::PARAM_CHECK_NEGATIVE_INT => \is_int($val) && $val < 0, - self::PARAM_CHECK_NON_POSITIVE_INT => \is_int($val) && $val <= 0, - self::PARAM_CHECK_NON_ZERO_INT => \is_int($val) && $val !== 0, - self::PARAM_CHECK_MIXED => true, - self::PARAM_CHECK_NULL => $val === null, - self::PARAM_CHECK_TRUE => $val === true, - self::PARAM_CHECK_FALSE => $val === false, - self::PARAM_CHECK_SCALAR => \is_scalar($val), - default => false, - }; - - if ($ok) { - continue; - } - - $err = $registry->validate($val, $item[2], '', $item[3]); - if ($err !== null) { - $formattedErr = ErrorFactory::createError($effectiveFunc . '(): Argument $' . $paramName . $err->getMessage()); - - if (IgnoreManager::isCallerIgnored()) { - return null; - } - - $handled = ViolationCollector::handle($formattedErr, 'parameter', null, function: $effectiveFunc); - if ($handled instanceof ErrorMessage) { - return $handled; - } - } - } - - return null; + if ( + $plan !== null + && ($plan['class'] === null + ? $thisOrClass === null + : (\is_object($thisOrClass) + ? $thisOrClass::class === $plan['class'] + : (! $plan['requireObject'] && $thisOrClass === $plan['class']))) + ) { + return self::executeSimpleScopePlan($plan, $vars); } - // Slow-path / initial execution & analysis $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + if ($effectiveFunction !== $function && isset(self::$simpleScopePlanCache[$effectiveFunction])) { + $effectivePlan = self::$simpleScopePlanCache[$effectiveFunction]; + if (! $effectivePlan['requireObject'] || $thisObj !== null) { + return self::executeSimpleScopePlan($effectivePlan, $vars); + } + } + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return null; } @@ -626,9 +580,10 @@ public static function setupScope(string $function, array $vars, object|string|n $registry = self::$registry ??= new TypeValidatorRegistry(); + $paramsAreSimple = $contract['paramsAreSimple'] ?? $contract['isSimple']; if ( ! $isMagicCall - && $contract['isSimple'] + && $paramsAreSimple && ($thisObj !== null || $contract['classTemplates'] === []) ) { $hasNoConditionals = ($contract['paramConditionals'] ?? null) === null || $contract['paramConditionals'] === []; @@ -640,13 +595,14 @@ public static function setupScope(string $function, array $vars, object|string|n $compiledPlan = [ 'class' => $declaringClass, + 'requireObject' => $contract['classTemplates'] !== [], 'function' => $effectiveFunction, 'items' => $compiledItems, ]; - self::$simpleScopePlanCache[$function] = $compiledPlan; - if ($function !== $effectiveFunction) { - self::$simpleScopePlanCache[$effectiveFunction] = $compiledPlan; + self::$simpleScopePlanCache[$effectiveFunction] = $compiledPlan; + if ($function === $effectiveFunction) { + self::$simpleScopePlanCache[$function] = $compiledPlan; } } @@ -719,6 +675,74 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } + /** + * @param array{class: ?string, requireObject: bool, function: string, items: list} $plan + * @param array $vars + */ + private static function executeSimpleScopePlan(array $plan, array $vars): ?ErrorMessage + { + if ($vars === []) { + return null; + } + + $registry = self::$registry ??= new TypeValidatorRegistry(); + $effectiveFunc = $plan['function']; + + foreach ($plan['items'] as $item) { + $paramName = $item[0]; + + if (isset($vars[$paramName])) { + $val = $vars[$paramName]; + } elseif (\array_key_exists($paramName, $vars)) { + $val = null; + } else { + continue; + } + + $ok = match ($item[1]) { + self::PARAM_CHECK_POSITIVE_INT => \is_int($val) && $val > 0, + self::PARAM_CHECK_NON_EMPTY_STRING => \is_string($val) && $val !== '', + self::PARAM_CHECK_INT => \is_int($val), + 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_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)), + self::PARAM_CHECK_NON_NEGATIVE_INT => \is_int($val) && $val >= 0, + self::PARAM_CHECK_NEGATIVE_INT => \is_int($val) && $val < 0, + self::PARAM_CHECK_NON_POSITIVE_INT => \is_int($val) && $val <= 0, + self::PARAM_CHECK_NON_ZERO_INT => \is_int($val) && $val !== 0, + self::PARAM_CHECK_MIXED => true, + self::PARAM_CHECK_NULL => $val === null, + self::PARAM_CHECK_TRUE => $val === true, + self::PARAM_CHECK_FALSE => $val === false, + self::PARAM_CHECK_SCALAR => \is_scalar($val), + default => false, + }; + + if ($ok) { + continue; + } + + $err = $registry->validate($val, $item[2], '', $item[3]); + if ($err !== null) { + $formattedErr = ErrorFactory::createError($effectiveFunc . '(): Argument $' . $paramName . $err->getMessage()); + + if (IgnoreManager::isCallerIgnored()) { + return null; + } + + $handled = ViolationCollector::handle($formattedErr, 'parameter', null, function: $effectiveFunc); + if ($handled instanceof ErrorMessage) { + return $handled; + } + } + } + + return null; + } + /** * @param array $types * @param array $sensitiveParams @@ -878,40 +902,31 @@ public static function checkReturn(string $function, mixed $value, object|string return $value; } - // Fast-path: pre-compiled simple return plan - if (isset(self::$simpleReturnPlanCache[$function])) { - $resolvedType = self::$simpleReturnPlanCache[$function]; - if ($resolvedType === false) { - return $value; - } - - $registry = self::$registry ??= new TypeValidatorRegistry(); - $err = $registry->validate($value, $resolvedType, 'Return value'); - if ($err !== null) { - if (IgnoreManager::isCallerIgnored()) { - return $value; - } - - $formattedErr = ErrorFactory::createError($function . '(): ' . $err->getMessage()); - - return ViolationCollector::handle($formattedErr, 'return', $value, function: $function, target: 'return'); - } - - return $value; + $retPlan = self::$simpleReturnPlanCache[$function] ?? null; + if ( + $retPlan !== null + && ($retPlan['class'] === null + ? $thisOrClass === null + : (\is_object($thisOrClass) ? $thisOrClass::class === $retPlan['class'] : $thisOrClass === $retPlan['class'])) + ) { + return self::executeSimpleReturnPlan($function, $retPlan['type'], $value); } - // Fast-path: bare class-template return (e.g. @return T on Box::unwrap()) if (isset(self::$genericReturnPlanCache[$function]) && \is_object($thisOrClass)) { $genPlan = self::$genericReturnPlanCache[$function]; if ($thisOrClass::class === $genPlan['class']) { $boundType = TemplateManager::getInstanceBoundTypeFast($thisOrClass, $genPlan['templateName']); if ($boundType instanceof IdentifierTypeNode) { $tName = $boundType->name; - if (\is_object($value) && ($value instanceof $tName) && ! ($value instanceof Traversable)) { - return $value; - } - - if ($tName === 'mixed' || $tName === 'array') { + if ( + ($tName === 'int' && \is_int($value)) + || ($tName === 'string' && \is_string($value)) + || ($tName === 'bool' && \is_bool($value)) + || ($tName === 'float' && (\is_float($value) || \is_int($value))) + || (\is_object($value) && ($value instanceof $tName) && ! ($value instanceof Traversable)) + || $tName === 'mixed' + || $tName === 'array' + ) { return $value; } } @@ -922,27 +937,9 @@ public static function checkReturn(string $function, mixed $value, object|string $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); if (isset(self::$simpleReturnPlanCache[$effectiveFunction])) { - $resolvedType = self::$simpleReturnPlanCache[$effectiveFunction]; - if ($resolvedType === false) { - return $value; - } - - $registry = self::$registry ??= new TypeValidatorRegistry(); - $err = $registry->validate($value, $resolvedType, 'Return value'); - if ($err !== null) { - if (IgnoreManager::isCallerIgnored()) { - return $value; - } - - $formattedErr = ErrorFactory::createError($effectiveFunction . '(): ' . $err->getMessage()); - - return ViolationCollector::handle($formattedErr, 'return', $value, function: $effectiveFunction, target: 'return'); - } - - return $value; + return self::executeSimpleReturnPlan($effectiveFunction, self::$simpleReturnPlanCache[$effectiveFunction]['type'], $value); } - // Slow-path / initial execution & analysis if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return $value; } @@ -955,9 +952,14 @@ public static function checkReturn(string $function, mixed $value, object|string } $contract = DocblockParser::parse($effectiveFunction); + $declaringClass = str_contains($effectiveFunction, '::') ? explode('::', $effectiveFunction, 2)[0] : null; + if (! $isDynamicDispatch && ($contract['returnUnconstrained'] ?? false)) { - self::$simpleReturnPlanCache[$function] = false; - self::$simpleReturnPlanCache[$effectiveFunction] = false; + $unconstrainedPlan = ['class' => $declaringClass, 'type' => false]; + self::$simpleReturnPlanCache[$effectiveFunction] = $unconstrainedPlan; + if ($function === $effectiveFunction) { + self::$simpleReturnPlanCache[$function] = $unconstrainedPlan; + } return $value; } @@ -968,8 +970,8 @@ public static function checkReturn(string $function, mixed $value, object|string if ( ! $isDynamicDispatch && $returnTypeNode !== null - && $contract['isSimple'] - && $contract['classTemplates'] === [] + && ! ($contract['returnUsesGenerics'] ?? true) + && \count($contract['aliases']) === 0 && ! ($contract['returnHasConditional'] ?? true) && ! $contract['returnIsDynamic'] && ! ($returnTypeNode instanceof CallableTypeNode) @@ -980,8 +982,11 @@ public static function checkReturn(string $function, mixed $value, object|string if ($resolvedType instanceof IdentifierTypeNode) { $lowerName = strtolower($resolvedType->name); if ($lowerName === 'mixed' || $lowerName === 'array') { - self::$simpleReturnPlanCache[$function] = false; - self::$simpleReturnPlanCache[$effectiveFunction] = false; + $unconstrainedPlan = ['class' => $declaringClass, 'type' => false]; + self::$simpleReturnPlanCache[$effectiveFunction] = $unconstrainedPlan; + if ($function === $effectiveFunction) { + self::$simpleReturnPlanCache[$function] = $unconstrainedPlan; + } return $value; } @@ -997,8 +1002,11 @@ public static function checkReturn(string $function, mixed $value, object|string } if (! $isTraversableIterable && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { - self::$simpleReturnPlanCache[$function] = $resolvedType; - self::$simpleReturnPlanCache[$effectiveFunction] = $resolvedType; + $compiledPlan = ['class' => $declaringClass, 'type' => $resolvedType]; + self::$simpleReturnPlanCache[$effectiveFunction] = $compiledPlan; + if ($function === $effectiveFunction) { + self::$simpleReturnPlanCache[$function] = $compiledPlan; + } } $err = $registry->validate($value, $resolvedType, 'Return value'); @@ -1031,8 +1039,7 @@ public static function checkReturn(string $function, mixed $value, object|string && ! ($contract['returnIsThis'] ?? false) && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) ) { - $declaringClass = str_contains($effectiveFunction, '::') ? explode('::', $effectiveFunction, 2)[0] : ''; - if ($declaringClass !== '' && $function === $effectiveFunction) { + if ($declaringClass !== null && $function === $effectiveFunction) { self::$genericReturnPlanCache[$function] = [ 'class' => $declaringClass, 'templateName' => $returnTypeNode->name, @@ -1064,6 +1071,27 @@ public static function checkReturn(string $function, mixed $value, object|string return $res; } + private static function executeSimpleReturnPlan(string $function, TypeNode|false $resolvedType, mixed $value): mixed + { + if ($resolvedType === false) { + return $value; + } + + $registry = self::$registry ??= new TypeValidatorRegistry(); + $err = $registry->validate($value, $resolvedType, 'Return value'); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + $formattedErr = ErrorFactory::createError($function . '(): ' . $err->getMessage()); + + return ViolationCollector::handle($formattedErr, 'return', $value, function: $function, target: 'return'); + } + + return $value; + } + /** * Validates a value sent into a generator via $gen->send() against TSend. */ diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index 90aab253..d5c9abb0 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -49,6 +49,33 @@ final class CallableWrapper */ private static array $specializedCallableCache = []; + /** + * Per-function/parameter metadata cache to avoid repeated parsing and conditional checks. + * + * @var array, + * hasMethodTemplates: bool, + * hasConditionals: bool, + * isDynamic: bool + * }>> + */ + private static array $callablePlanCache = []; + + /** + * Cache for resolved non-conditional callable TypeNodes keyed by [$effectiveFunction][$paramName][$sig]. + * + * @var array>> + */ + private static array $wrappedNodeCache = []; + + public static function reset(): void + { + self::$specializedCallableCache = []; + self::$callablePlanCache = []; + self::$wrappedNodeCache = []; + } + /** * Safely checks if a value is callable without triggering PHP 8.2+ deprecation warnings * on partially supported callables (e.g. 'static::method', ['static', 'method']). @@ -91,25 +118,18 @@ public static function isCallable(mixed $value): bool */ public static function wrap(string $function, string $paramName, mixed $callable, TypeValidatorRegistry $registry, object|string|null $thisOrClass = null): mixed { - $contract = DocblockParser::parse($function); - $typeNode = ($paramName === 'return') ? ($contract['return'] ?? null) : ($contract['types'][$paramName] ?? null); - $aliases = $contract['aliases'] ?? []; - $templates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; - - if ($typeNode instanceof IdentifierTypeNode && isset($aliases[$typeNode->name])) { - $typeNode = $aliases[$typeNode->name]; + if ($callable === null || (! \is_array($callable) && ! self::isCallable($callable))) { + return $callable; } $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); - - if ($typeNode !== null && (\count($boundTemplates) > 0 || \count($templates) > 0)) { - $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); - $typeNode = SpecialTypeResolver::resolve($typeNode, $function, $thisObj); - } + $effectiveFunction = $thisOrClass !== null + ? \TypePHP\Internal\Checker\ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj) + : $function; - if ($typeNode !== null && ConditionalChecker::containsConditional($typeNode)) { - $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $function); + $typeNode = self::resolveCallableParamTypeNode($effectiveFunction, $paramName, $thisObj, $registry); + if ($typeNode === null) { + return $callable; } $prefix = ($paramName === 'return') ? "$function(): Return value" : "$function(): Callback \$$paramName"; @@ -118,7 +138,7 @@ public static function wrap(string $function, string $paramName, mixed $callable return self::wrapTypeNode($typeNode, $callable, $prefix, $registry, $function, $paramName); } - if (\is_array($callable) && $typeNode !== null) { + if (\is_array($callable)) { $innerCallableTypeNode = null; if ($typeNode instanceof GenericTypeNode && \in_array(strtolower((string) $typeNode->type), ['list', 'array', 'iterable'], strict: true)) { @@ -145,6 +165,95 @@ public static function wrap(string $function, string $paramName, mixed $callable return $callable; } + private static function resolveCallableParamTypeNode( + string $effectiveFunction, + string $paramName, + ?object $thisObj, + TypeValidatorRegistry $registry + ): ?TypeNode { + if (! isset(self::$callablePlanCache[$effectiveFunction]) || ! \array_key_exists($paramName, self::$callablePlanCache[$effectiveFunction])) { + $contract = DocblockParser::parse($effectiveFunction); + $rawTypeNode = ($paramName === 'return') + ? ($contract['return'] ?? null) + : ($contract['types'][$paramName] ?? null); + + if ($rawTypeNode === null) { + self::$callablePlanCache[$effectiveFunction][$paramName] = null; + + return null; + } + + $aliases = $contract['aliases'] ?? []; + if ($rawTypeNode instanceof IdentifierTypeNode && isset($aliases[$rawTypeNode->name])) { + $rawTypeNode = $aliases[$rawTypeNode->name]; + } + + $templates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; + + self::$callablePlanCache[$effectiveFunction][$paramName] = [ + 'typeNode' => $rawTypeNode, + 'templates' => $templates, + 'hasMethodTemplates' => ($contract['templates'] ?? []) !== [], + 'hasConditionals' => ConditionalChecker::containsConditional($rawTypeNode), + 'isDynamic' => str_contains((string) $rawTypeNode, 'static') || str_contains((string) $rawTypeNode, '$this'), + ]; + } + + $plan = self::$callablePlanCache[$effectiveFunction][$paramName]; + if ($plan === null) { + return null; + } + + $templates = $plan['templates']; + $boundTemplates = []; + if ($templates !== []) { + $boundTemplates = ($thisObj !== null && ! $plan['hasMethodTemplates']) + ? TemplateManager::getInstanceBindingsFast($thisObj) + : TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $templates); + } + + $sig = null; + if (! $plan['hasConditionals'] && ! $plan['isDynamic'] && \count($boundTemplates) <= 2) { + if ($boundTemplates === []) { + $sig = ''; + } elseif (\count($boundTemplates) === 1) { + $firstKey = (string) array_key_first($boundTemplates); + $first = $boundTemplates[$firstKey]; + $sig = $firstKey . '=' . ($first instanceof IdentifierTypeNode ? $first->name : (string) $first); + } else { + $sig = ''; + foreach ($boundTemplates as $k => $v) { + $sig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; + } + } + + if (isset(self::$wrappedNodeCache[$effectiveFunction][$paramName][$sig])) { + return self::$wrappedNodeCache[$effectiveFunction][$paramName][$sig]; + } + } + + $typeNode = $plan['typeNode']; + + if ($boundTemplates !== [] || $templates !== []) { + $subNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); + if ($subNode !== $typeNode || $plan['isDynamic']) { + $typeNode = SpecialTypeResolver::resolve($subNode, $effectiveFunction, $thisObj); + } + } elseif ($plan['isDynamic']) { + $typeNode = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); + } + + if ($plan['hasConditionals'] || (! ($typeNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($typeNode))) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $effectiveFunction); + } + + if ($sig !== null) { + self::$wrappedNodeCache[$effectiveFunction][$paramName][$sig] = $typeNode; + } + + return $typeNode; + } + /** * Wraps a callable with runtime argument and return value type validation based on a CallableTypeNode AST. */ From 5302c472467334caaaaf177b2395a39774adcd01 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 19 Nov 2026 14:15:58 +0800 Subject: [PATCH 11/25] Enhance type checking and caching mechanisms in ConditionalChecker, GeneratorChecker, MemberAssignChecker, TemplateManager, RuntimeTypeChecker, and IterableWrapper for improved performance and reliability --- src/Internal/Checker/ConditionalChecker.php | 23 +++ src/Internal/Checker/GeneratorChecker.php | 30 ++-- src/Internal/Checker/MemberAssignChecker.php | 83 ++++++--- src/Internal/Generics/TemplateManager.php | 29 ++- src/Internal/RuntimeTypeChecker.php | 27 +-- src/Internal/Wrapper/IterableWrapper.php | 177 ++++++++++++++----- 6 files changed, 279 insertions(+), 90 deletions(-) diff --git a/src/Internal/Checker/ConditionalChecker.php b/src/Internal/Checker/ConditionalChecker.php index ebc776e3..89f81f7e 100644 --- a/src/Internal/Checker/ConditionalChecker.php +++ b/src/Internal/Checker/ConditionalChecker.php @@ -33,10 +33,33 @@ */ final class ConditionalChecker { + /** + * @var \WeakMap|null + */ + private static ?\WeakMap $containsConditionalCache = null; + /** * Checks whether a TypeNode AST contains any conditional types. */ public static function containsConditional(TypeNode $node): bool + { + if ($node instanceof IdentifierTypeNode) { + return false; + } + + if ($node instanceof ConditionalTypeNode || $node instanceof ConditionalTypeForParameterNode) { + return true; + } + + self::$containsConditionalCache ??= new \WeakMap(); + if (isset(self::$containsConditionalCache[$node])) { + return self::$containsConditionalCache[$node]; + } + + return self::$containsConditionalCache[$node] = self::computeContainsConditional($node); + } + + private static function computeContainsConditional(TypeNode $node): bool { while ($node instanceof NullableTypeNode || $node instanceof ArrayTypeNode) { $node = $node->type; diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index 6e3d191d..c2885274 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -106,10 +106,10 @@ final class GeneratorChecker private static array $genericYieldTypeCache = []; /** - * Per-instance yield contract cache keyed by object identity and raw bindings equality. + * Per-instance yield contract cache keyed by object identity and TemplateManager's instance bindings version. * * @var WeakMap, + * version: int, * types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed} * }>>|null */ @@ -331,6 +331,14 @@ private static function resolveYieldAndSendTypes( && ! $plan['hasConditionals'] && ! $plan['isDynamic']; + if ($canUseInstanceCache) { + self::$instanceYieldCache ??= new WeakMap(); + $cachedEntry = self::$instanceYieldCache[$thisObj][$function] ?? null; + if ($cachedEntry !== null && $cachedEntry['version'] === TemplateManager::$instanceBindingsVersion) { + return $cachedEntry['types']; + } + } + $boundTemplates = []; if ($scopeCleaner !== null && $scopeCleaner->boundTemplates !== []) { $boundTemplates = $scopeCleaner->boundTemplates; @@ -340,14 +348,6 @@ private static function resolveYieldAndSendTypes( : TemplateManager::getBoundTemplates($function, $thisOrClass, $allTemplates); } - if ($canUseInstanceCache) { - self::$instanceYieldCache ??= new WeakMap(); - $cachedEntry = self::$instanceYieldCache[$thisObj][$function] ?? null; - if ($cachedEntry !== null && $cachedEntry['bindings'] === $boundTemplates) { - return $cachedEntry['types']; - } - } - $sig = null; if (! $plan['hasAliases'] && ! $plan['hasConditionals'] && ! $plan['isDynamic'] && $scopeCleaner === null) { if ($boundTemplates === []) { @@ -366,9 +366,9 @@ private static function resolveYieldAndSendTypes( if ($sig !== null && isset(self::$genericYieldTypeCache[$function][$sig])) { $types = self::$genericYieldTypeCache[$function][$sig]; if ($canUseInstanceCache) { - /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}}> $mapEntry */ + /** @var array $mapEntry */ $mapEntry = self::$instanceYieldCache[$thisObj] ?? []; - $mapEntry[$function] = ['bindings' => $boundTemplates, 'types' => $types]; + $mapEntry[$function] = ['version' => TemplateManager::$instanceBindingsVersion, 'types' => $types]; self::$instanceYieldCache[$thisObj] = $mapEntry; } @@ -402,9 +402,9 @@ private static function resolveYieldAndSendTypes( } if ($canUseInstanceCache) { - /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}}> $mapEntry */ + /** @var array $mapEntry */ $mapEntry = self::$instanceYieldCache[$thisObj] ?? []; - $mapEntry[$function] = ['bindings' => $boundTemplates, 'types' => $types]; + $mapEntry[$function] = ['version' => TemplateManager::$instanceBindingsVersion, 'types' => $types]; self::$instanceYieldCache[$thisObj] = $mapEntry; } @@ -546,4 +546,4 @@ private static function matchesMask(mixed $value, int $mask): bool return false; } -} +} \ No newline at end of file diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 1c59f2d6..b1b4270d 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -97,10 +97,10 @@ final class MemberAssignChecker private static array $substitutedElementContractCache = []; /** - * Per-instance contract cache keyed by object identity and raw bindings equality. + * Per-instance contract cache keyed by object identity and global bindings version. * * @var WeakMap, + * version: int, * contracts: array \is_int($key), + self::OP_STRING => \is_string($key), + self::OP_ARRAY_KEY => \is_int($key) || \is_string($key), + self::OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', + self::OP_POSITIVE_INT => \is_int($key) && $key > 0, + self::OP_MASK => ( + (\is_string($key) && (((int) $keyExtra) & self::BIT_STRING) !== 0) + || (\is_int($key) && (((int) $keyExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($key) && (((int) $keyExtra) & self::BIT_OBJECT) !== 0) + || (\is_bool($key) && (((int) $keyExtra) & self::BIT_BOOL) !== 0) + || (\is_float($key) && (((int) $keyExtra) & self::BIT_FLOAT) !== 0) + || (\is_array($key) && (((int) $keyExtra) & self::BIT_ARRAY) !== 0) + ), + self::OP_OBJECT => \is_object($key), + self::OP_CLASS => \is_object($key) && ($key instanceof $keyExtra), + default => false, + }; + } + + $valOk = true; + if ($keyOk && $contract['valOp'] !== self::OP_NONE) { + $valExtra = $contract['valExtra']; + $valOk = match ($contract['valOp']) { + self::OP_INT => \is_int($value), + self::OP_STRING => \is_string($value), + self::OP_BOOL => \is_bool($value), + self::OP_FLOAT => \is_float($value) || \is_int($value), + self::OP_POSITIVE_INT => \is_int($value) && $value > 0, + self::OP_NON_EMPTY_STRING => \is_string($value) && $value !== '', + self::OP_ARRAY_KEY => \is_int($value) || \is_string($value), + self::OP_ARRAY => \is_array($value), + self::OP_OBJECT => \is_object($value), + self::OP_CLASS => \is_object($value) && ($value instanceof $valExtra), + self::OP_MASK => ( + (\is_string($value) && (((int) $valExtra) & self::BIT_STRING) !== 0) + || (\is_int($value) && (((int) $valExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($value) && (((int) $valExtra) & self::BIT_OBJECT) !== 0) + || (\is_bool($value) && (((int) $valExtra) & self::BIT_BOOL) !== 0) + || (\is_float($value) && (((int) $valExtra) & self::BIT_FLOAT) !== 0) + || ($value === null && (((int) $valExtra) & self::BIT_NULL) !== 0) + || (\is_array($value) && (((int) $valExtra) & self::BIT_ARRAY) !== 0) + ), + default => false, + }; + } + + if ($keyOk && $valOk) { return $value; } } @@ -520,19 +560,22 @@ private static function resolveElementContractFromPlan( ): ?array { $boundTemplates = []; $useInstanceCache = $propPlan['usesTemplates'] && \is_object($objectOrClass); + $currentVersion = TemplateManager::$instanceBindingsVersion; if ($useInstanceCache) { - $boundTemplates = $preFetchedBindings ?? TemplateManager::getInstanceBindingsFast($objectOrClass); self::$instanceContractCache ??= new WeakMap(); $entry = self::$instanceContractCache[$objectOrClass] ?? null; if ( $entry !== null - && $entry['rawBindings'] === $boundTemplates + && $entry['version'] === $currentVersion && \array_key_exists($propName, $entry['contracts']) ) { return $entry['contracts'][$propName]; } + + $boundTemplates = $preFetchedBindings ?? TemplateManager::getInstanceBindingsFast($objectOrClass); + $currentVersion = TemplateManager::$instanceBindingsVersion; } $sig = ''; @@ -556,9 +599,9 @@ private static function resolveElementContractFromPlan( if ($useInstanceCache) { $entry = self::$instanceContractCache[$objectOrClass] ?? null; - if ($entry === null || $entry['rawBindings'] !== $boundTemplates) { + if ($entry === null || $entry['version'] !== $currentVersion) { self::$instanceContractCache[$objectOrClass] = [ - 'rawBindings' => $boundTemplates, + 'version' => $currentVersion, 'contracts' => [$propName => $contract], ]; } else { @@ -747,4 +790,4 @@ private static function getReflectionProperty(string $className, string $propNam return self::$refPropertyCache[$className][$propName] = null; } -} +} \ No newline at end of file diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index d5ea29e3..dd8b1beb 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -119,6 +119,11 @@ final class TemplateManager */ public static ?object $pendingCloneSource = null; + /** + * Monotonic version bumped whenever any instance's template bindings are written. + */ + public static int $instanceBindingsVersion = 0; + /** * Fast O(1) hashmap for recognized key template names. * @@ -568,6 +573,7 @@ public static function reset(): void self::$subclassCache = []; self::$realTypeSymbolCache = []; self::$pendingCloneSource = null; + self::$instanceBindingsVersion = 0; self::$methodTemplatesCache = []; self::$isMethodTemplateCache = []; self::$isFBoundCache = []; @@ -598,6 +604,8 @@ public static function restoreInstanceBindings(object $instance, array $bindings } else { self::$instanceTemplateBindings[$instance] = $bindings; } + + self::$instanceBindingsVersion++; } /** @@ -770,6 +778,7 @@ public static function copyInstanceBindings(object $source, object $target): voi $bindings = self::$instanceTemplateBindings[$source]; $bindings = self::widenClonedBindingsFromActiveCall($target, $bindings); self::$instanceTemplateBindings[$target] = $bindings; + self::$instanceBindingsVersion++; } if (self::isGeneratorInferred($source)) { @@ -1011,7 +1020,7 @@ public static function getInstanceBindingsFast(object $instance): array } } - $defaults = self::classTemplateDefaults($className); + $defaults = self::$classTemplateDefaultsCache[$className] ?? self::classTemplateDefaults($className); if ($defaults !== []) { foreach ($defaults as $tName => $default) { if (! isset($bindings[$tName])) { @@ -1195,6 +1204,7 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ } self::$instanceTemplateBindings[$thisObj] = $bindings; + self::$instanceBindingsVersion++; } else { if (! self::hasCallFrame($function)) { self::$callStackBindings[$function][] = []; @@ -1303,6 +1313,13 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t continue; } + if ( + $existingTypeNode::class === $expectedTypeNode::class + && (string) $existingTypeNode === (string) $expectedTypeNode + ) { + continue; + } + $allFastMatched = false; break; @@ -1525,6 +1542,7 @@ public static function applyClassTemplateDefaults(object $instance, array $class if ($changed) { self::$instanceTemplateBindings[$instance] = $bindings; + self::$instanceBindingsVersion++; } } @@ -2010,6 +2028,7 @@ private static function bindSingleTemplateArgument( } self::$instanceTemplateBindings[$instance] = $bindings; + self::$instanceBindingsVersion++; if ($isReturnContext && self::isGeneratorInferred($instance)) { self::propagateGeneratorRefinementToProperties($instance, $templateName, $expectedTypeNode); @@ -2027,6 +2046,7 @@ private static function bindSingleTemplateArgument( $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; self::$instanceTemplateBindings[$instance] = $bindings; + self::$instanceBindingsVersion++; return null; } @@ -2043,6 +2063,7 @@ private static function bindSingleTemplateArgument( $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; self::$instanceTemplateBindings[$instance] = $bindings; + self::$instanceBindingsVersion++; return null; } @@ -2083,6 +2104,7 @@ private static function bindSingleTemplateArgument( } $map[$instance] = $bindings; + self::$instanceBindingsVersion++; } return null; @@ -2122,6 +2144,7 @@ private static function propagateGeneratorRefinementToProperties(object $instanc } } $map[$propVal] = $propBindings; + self::$instanceBindingsVersion++; } } } catch (\Throwable) { @@ -2282,6 +2305,7 @@ public static function resolveInheritedTemplates(object $instance, string $targe if ($existing === []) { if ($cachedBindings !== []) { self::$instanceTemplateBindings[$instance] = $cachedBindings; + self::$instanceBindingsVersion++; } return; @@ -2306,6 +2330,7 @@ public static function resolveInheritedTemplates(object $instance, string $targe $merged = [...$existing, ...$specializedBindings]; if ($merged !== [] && $merged !== $existing) { self::$instanceTemplateBindings[$instance] = $merged; + self::$instanceBindingsVersion++; } } @@ -3475,4 +3500,4 @@ private static function resolveTypeNodeAst(TypeNode $n, \ReflectionClass $ref): return $n; } -} +} \ No newline at end of file diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index cd7db747..d5223544 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -136,6 +136,7 @@ public static function reset(): void GeneratorChecker::reset(); ViolationCollector::reset(); CallableWrapper::reset(); + IterableWrapper::reset(); } /** @@ -294,11 +295,6 @@ public static function checkPropertyMemberAssign( return $value; } - $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); - if ($className !== '' && isset(InlineChecker::$nullPropertyCache[$className][$propName])) { - return $value; - } - $res = MemberAssignChecker::checkProperty( $objectOrClass, $propName, @@ -309,6 +305,7 @@ public static function checkPropertyMemberAssign( ); if ($res instanceof ErrorMessage) { + $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName)) { return $value; } @@ -1101,7 +1098,7 @@ public static function checkSend( object|string|null $thisOrClass = null, ?ScopeCleaner $scopeCleaner = null ): mixed { - if (! self::$isEnabled) { + if ($sendValue === null || ! self::$isEnabled) { return $sendValue; } @@ -1173,13 +1170,17 @@ public static function checkYield( } $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + if ($thisObj !== null && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$function]) && str_starts_with($function, $thisObj::class . '::')) { + $effectiveFunction = $function; + } else { + $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); - if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { - return $value; + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { + return $value; + } } - $res = GeneratorChecker::checkYield($function, $key, $value, self::getRegistry(), $thisOrClass, $scopeCleaner, $effectiveFunction); + $res = GeneratorChecker::checkYield($function, $key, $value, self::$registry ??= new TypeValidatorRegistry(), $thisOrClass, $scopeCleaner, $effectiveFunction); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { @@ -1216,18 +1217,18 @@ public static function wrapCallable(string $function, string $paramName, mixed $ */ public static function wrapIterable(string $function, string $paramName, mixed $iterable, object|string|null $thisOrClass = null): mixed { - if (! self::$isEnabled) { + if (! self::$isEnabled || (\is_array($iterable) && $paramName !== 'return') || ! is_iterable($iterable)) { return $iterable; } $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); - if (CallerBoundaryResolver::shouldBypass($effectiveFunction)) { + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return $iterable; } - return IterableWrapper::wrap($function, $paramName, $iterable, self::getRegistry(), $thisOrClass); + return IterableWrapper::wrap($function, $paramName, $iterable, self::$registry ??= new TypeValidatorRegistry(), $thisOrClass); } /** diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index 1a9e15a7..71886bc5 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -31,10 +31,38 @@ final class IterableWrapper { /** - * Wraps Traversable iterators and Generators to lazily validate keys and values during iteration. + * @var array, + * templates: array, + * hasMethodTemplates: bool, + * hasConditionals: bool, + * isDynamic: bool + * }>> */ - public static function wrap(string $function, string $paramName, mixed $iterable, TypeValidatorRegistry $registry, object|string|null $thisOrClass = null): mixed + private static array $iterablePlanCache = []; + + /** + * @var array>> + */ + private static array $resolvedIterableCache = []; + + public static function reset(): void { + self::$iterablePlanCache = []; + self::$resolvedIterableCache = []; + } + + /** + * Wraps Traversable iterators and Generators to lazily validate keys and values during iteration. + */ + public static function wrap( + string $function, + string $paramName, + mixed $iterable, + TypeValidatorRegistry $registry, + object|string|null $thisOrClass = null + ): mixed { if (! is_iterable($iterable)) { return $iterable; } @@ -43,69 +71,138 @@ public static function wrap(string $function, string $paramName, mixed $iterable return $iterable; } - $contract = DocblockParser::parse($function); - $typeNode = ($paramName === 'return') ? ($contract['return'] ?? null) : ($contract['types'][$paramName] ?? null); - - if ($typeNode === null) { + $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; + $keyAndItem = self::resolveKeyAndItemTypes($function, $paramName, $thisObj, $registry); + if ($keyAndItem === null) { return $iterable; } - $aliases = $contract['aliases'] ?? []; - $templates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; + [$keyTypeNode, $itemTypeNode] = $keyAndItem; - $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + $prefix = ($paramName === 'return') ? "$function(): Return iterator" : "$function(): Iterator \$$paramName"; + $typeCheckCallback = self::createValidationCallback($registry, $keyTypeNode, $itemTypeNode, $prefix, $function); - if (ConditionalChecker::containsConditional($typeNode)) { - $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $function); + if (\is_array($iterable)) { + return self::wrapGenerator((function () use ($iterable) { + yield from $iterable; + })(), $typeCheckCallback); } - if (\count($boundTemplates) > 0 || \count($templates) > 0) { - $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); - $typeNode = SpecialTypeResolver::resolve($typeNode, $function, $thisObj); + if (! ($iterable instanceof Generator)) { + return new IteratorProxy($iterable, $typeCheckCallback); } - if (ConditionalChecker::containsConditional($typeNode)) { - $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $function); + return self::wrapGenerator($iterable, $typeCheckCallback); + } + + /** + * @return array{0: ?TypeNode, 1: ?TypeNode}|null + */ + private static function resolveKeyAndItemTypes( + string $effectiveFunction, + string $paramName, + ?object $thisObj, + TypeValidatorRegistry $registry + ): ?array { + if (! isset(self::$iterablePlanCache[$effectiveFunction]) || ! \array_key_exists($paramName, self::$iterablePlanCache[$effectiveFunction])) { + $contract = DocblockParser::parse($effectiveFunction); + $typeNode = ($paramName === 'return') ? ($contract['return'] ?? null) : ($contract['types'][$paramName] ?? null); + + if ($typeNode === null) { + self::$iterablePlanCache[$effectiveFunction][$paramName] = null; + + return null; + } + + $templates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; + + self::$iterablePlanCache[$effectiveFunction][$paramName] = [ + 'typeNode' => $typeNode, + 'aliases' => $contract['aliases'] ?? [], + 'templates' => $templates, + 'hasMethodTemplates' => ($contract['templates'] ?? []) !== [], + 'hasConditionals' => ConditionalChecker::containsConditional($typeNode), + 'isDynamic' => str_contains((string) $typeNode, 'static') || str_contains((string) $typeNode, '$this'), + ]; } - if (\count($boundTemplates) > 0 || \count($templates) > 0) { - $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); - $typeNode = SpecialTypeResolver::resolve($typeNode, $function, $thisObj); + $plan = self::$iterablePlanCache[$effectiveFunction][$paramName]; + if ($plan === null) { + return null; } - $baseName = ''; - if ($typeNode instanceof IdentifierTypeNode) { - $baseName = strtolower(ltrim($typeNode->name, '\\')); - } elseif ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); + $templates = $plan['templates']; + $boundTemplates = []; + if ($templates !== []) { + $boundTemplates = ($thisObj !== null && ! $plan['hasMethodTemplates']) + ? TemplateManager::getInstanceBindingsFast($thisObj) + : TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $templates); } - $standardIterables = ['iterable', 'traversable', 'iterator', 'generator']; - if (! \in_array($baseName, $standardIterables, strict: true)) { - return $iterable; + $sig = null; + if (! $plan['hasConditionals'] && ! $plan['isDynamic'] && \count($boundTemplates) <= 2) { + if ($boundTemplates === []) { + $sig = ''; + } elseif (\count($boundTemplates) === 1) { + $firstKey = (string) array_key_first($boundTemplates); + $first = $boundTemplates[$firstKey]; + $sig = $firstKey . '=' . ($first instanceof IdentifierTypeNode ? $first->name : (string) $first); + } else { + $sig = ''; + foreach ($boundTemplates as $k => $v) { + $sig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; + } + } + + if (isset(self::$resolvedIterableCache[$effectiveFunction][$paramName]) && \array_key_exists($sig, self::$resolvedIterableCache[$effectiveFunction][$paramName])) { + return self::$resolvedIterableCache[$effectiveFunction][$paramName][$sig]; + } } - [$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($typeNode, $aliases); + $typeNode = $plan['typeNode']; - if (self::isUnconstrainedKey($keyTypeNode) && self::isUnconstrained($itemTypeNode)) { - return $iterable; + if ($plan['hasConditionals']) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $effectiveFunction); } - $prefix = ($paramName === 'return') ? "$function(): Return iterator" : "$function(): Iterator \$$paramName"; - $typeCheckCallback = self::createValidationCallback($registry, $keyTypeNode, $itemTypeNode, $prefix, $function); + if ($boundTemplates !== [] || $templates !== []) { + $subNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); + if ($subNode !== $typeNode || $plan['isDynamic']) { + $typeNode = SpecialTypeResolver::resolve($subNode, $effectiveFunction, $thisObj); + } + } elseif ($plan['isDynamic']) { + $typeNode = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); + } - if (\is_array($iterable)) { - return self::wrapGenerator((function () use ($iterable) { - yield from $iterable; - })(), $typeCheckCallback); + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $effectiveFunction); + if ($boundTemplates !== [] || $templates !== []) { + $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); + $typeNode = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); + } } - if (! ($iterable instanceof Generator)) { - return new IteratorProxy($iterable, $typeCheckCallback); + $baseName = ''; + if ($typeNode instanceof IdentifierTypeNode) { + $baseName = strtolower(ltrim($typeNode->name, '\\')); + } elseif ($typeNode instanceof GenericTypeNode) { + $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); } - return self::wrapGenerator($iterable, $typeCheckCallback); + $result = null; + $standardIterables = ['iterable', 'traversable', 'iterator', 'generator']; + if (\in_array($baseName, $standardIterables, strict: true)) { + [$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($typeNode, $plan['aliases']); + if (! self::isUnconstrainedKey($keyTypeNode) || ! self::isUnconstrained($itemTypeNode)) { + $result = [$keyTypeNode, $itemTypeNode]; + } + } + + if ($sig !== null) { + self::$resolvedIterableCache[$effectiveFunction][$paramName][$sig] = $result; + } + + return $result; } /** From dead3884eb31d56112eeebb261b8b14ba091f9dc Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 19 Nov 2026 16:13:29 +0800 Subject: [PATCH 12/25] Massively improve performance in Various internal components --- src/Internal/Ast/ScopeCleaner.php | 7 + src/Internal/Checker/GeneratorChecker.php | 93 +++--- src/Internal/Checker/MemberAssignChecker.php | 92 ++++-- src/Internal/Checker/ParamChecker.php | 151 ++++++++- src/Internal/Checker/ReturnChecker.php | 4 +- src/Internal/Generics/TemplateManager.php | 202 ++++++++---- src/Internal/RuntimeTypeChecker.php | 293 +++++++++++++++++- .../Validator/TypeValidatorRegistry.php | 8 +- src/Internal/Wrapper/CallableWrapper.php | 111 +++++++ src/Internal/Wrapper/IterableWrapper.php | 94 +++--- 10 files changed, 864 insertions(+), 191 deletions(-) diff --git a/src/Internal/Ast/ScopeCleaner.php b/src/Internal/Ast/ScopeCleaner.php index 4fe36ef2..081f0cef 100644 --- a/src/Internal/Ast/ScopeCleaner.php +++ b/src/Internal/Ast/ScopeCleaner.php @@ -19,6 +19,13 @@ final class ScopeCleaner */ public array $boundTemplates = []; + /** + * Cached resolved yield, send, and return contract tuple for the current generator execution scope. + * + * @var array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}|null + */ + public ?array $resolvedYieldTypes = null; + public function __construct(private string $function) { } diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index c2885274..0b6faafb 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -106,10 +106,10 @@ final class GeneratorChecker private static array $genericYieldTypeCache = []; /** - * Per-instance yield contract cache keyed by object identity and TemplateManager's instance bindings version. + * Per-instance yield contract cache keyed by object identity and raw instance bindings. * * @var WeakMap, * types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed} * }>>|null */ @@ -140,7 +140,9 @@ public static function checkSend( } $targetFunction = $effectiveFunction !== '' ? $effectiveFunction : $function; - $types = self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); + $types = ($scopeCleaner !== null && $scopeCleaner->resolvedYieldTypes !== null) + ? $scopeCleaner->resolvedYieldTypes + : self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $sendValue; } @@ -168,7 +170,9 @@ public static function checkYield( string $effectiveFunction = '' ): mixed { $targetFunction = $effectiveFunction !== '' ? $effectiveFunction : $function; - $types = self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); + $types = ($scopeCleaner !== null && $scopeCleaner->resolvedYieldTypes !== null) + ? $scopeCleaner->resolvedYieldTypes + : self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $value; } @@ -186,7 +190,14 @@ public static function checkYield( self::OP_FLOAT => \is_float($key) || \is_int($key), self::OP_OBJECT => \is_object($key), self::OP_CLASS => \is_object($key) && ($key instanceof $keyExtra), - self::OP_MASK => self::matchesMask($key, (int) $keyExtra), + self::OP_MASK => ( + (\is_string($key) && (((int) $keyExtra) & self::BIT_STRING) !== 0) + || (\is_int($key) && (((int) $keyExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($key) && (((int) $keyExtra) & self::BIT_OBJECT) !== 0) + || (\is_bool($key) && (((int) $keyExtra) & self::BIT_BOOL) !== 0) + || (\is_float($key) && (((int) $keyExtra) & self::BIT_FLOAT) !== 0) + || (\is_array($key) && (((int) $keyExtra) & self::BIT_ARRAY) !== 0) + ), default => false, }; @@ -212,7 +223,15 @@ public static function checkYield( self::OP_ARRAY => \is_array($value), self::OP_OBJECT => \is_object($value), self::OP_CLASS => \is_object($value) && ($value instanceof $valExtra), - self::OP_MASK => self::matchesMask($value, (int) $valExtra), + self::OP_MASK => ( + (\is_string($value) && (((int) $valExtra) & self::BIT_STRING) !== 0) + || (\is_int($value) && (((int) $valExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($value) && (((int) $valExtra) & self::BIT_OBJECT) !== 0) + || (\is_bool($value) && (((int) $valExtra) & self::BIT_BOOL) !== 0) + || (\is_float($value) && (((int) $valExtra) & self::BIT_FLOAT) !== 0) + || ($value === null && (((int) $valExtra) & self::BIT_NULL) !== 0) + || (\is_array($value) && (((int) $valExtra) & self::BIT_ARRAY) !== 0) + ), default => false, }; @@ -239,7 +258,9 @@ public static function checkReturn( string $effectiveFunction = '' ): mixed { $targetFunction = $effectiveFunction !== '' ? $effectiveFunction : $function; - $types = self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); + $types = ($scopeCleaner !== null && $scopeCleaner->resolvedYieldTypes !== null) + ? $scopeCleaner->resolvedYieldTypes + : self::resolveYieldAndSendTypes($targetFunction, $thisOrClass, $registry, $scopeCleaner); if ($types === null) { return $value; } @@ -303,8 +324,12 @@ private static function resolveYieldAndSendTypes( if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && ! $isDynamic) { $resolvedNode = SpecialTypeResolver::resolve($returnTypeNode, $function, null); + $types = self::$staticYieldTypeCache[$function] = self::compileYieldTypes($resolvedNode); + if ($scopeCleaner !== null) { + $scopeCleaner->resolvedYieldTypes = $types; + } - return self::$staticYieldTypeCache[$function] = self::compileYieldTypes($resolvedNode); + return $types; } self::$generatorPlanCache[$function] = [ @@ -334,7 +359,10 @@ private static function resolveYieldAndSendTypes( if ($canUseInstanceCache) { self::$instanceYieldCache ??= new WeakMap(); $cachedEntry = self::$instanceYieldCache[$thisObj][$function] ?? null; - if ($cachedEntry !== null && $cachedEntry['version'] === TemplateManager::$instanceBindingsVersion) { + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$thisObj] ?? null) + : null; + if ($cachedEntry !== null && $cachedEntry['rawBindings'] === $rawBindings) { return $cachedEntry['types']; } } @@ -366,9 +394,12 @@ private static function resolveYieldAndSendTypes( if ($sig !== null && isset(self::$genericYieldTypeCache[$function][$sig])) { $types = self::$genericYieldTypeCache[$function][$sig]; if ($canUseInstanceCache) { - /** @var array $mapEntry */ + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$thisObj] ?? null) + : null; + /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}}> $mapEntry */ $mapEntry = self::$instanceYieldCache[$thisObj] ?? []; - $mapEntry[$function] = ['version' => TemplateManager::$instanceBindingsVersion, 'types' => $types]; + $mapEntry[$function] = ['rawBindings' => $rawBindings, 'types' => $types]; self::$instanceYieldCache[$thisObj] = $mapEntry; } @@ -402,12 +433,19 @@ private static function resolveYieldAndSendTypes( } if ($canUseInstanceCache) { - /** @var array $mapEntry */ + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$thisObj] ?? null) + : null; + /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}}> $mapEntry */ $mapEntry = self::$instanceYieldCache[$thisObj] ?? []; - $mapEntry[$function] = ['version' => TemplateManager::$instanceBindingsVersion, 'types' => $types]; + $mapEntry[$function] = ['rawBindings' => $rawBindings, 'types' => $types]; self::$instanceYieldCache[$thisObj] = $mapEntry; } + if ($scopeCleaner !== null) { + $scopeCleaner->resolvedYieldTypes = $types; + } + return $types; } @@ -519,31 +557,4 @@ private static function compileCheckOp(?TypeNode $typeNode): array return [self::OP_FALLBACK, null]; } - - private static function matchesMask(mixed $value, int $mask): bool - { - if (\is_string($value)) { - return ($mask & self::BIT_STRING) !== 0; - } - if (\is_int($value)) { - return ($mask & (self::BIT_INT | self::BIT_FLOAT)) !== 0; - } - if (\is_object($value)) { - return ($mask & self::BIT_OBJECT) !== 0; - } - if (\is_bool($value)) { - return ($mask & self::BIT_BOOL) !== 0; - } - if (\is_float($value)) { - return ($mask & self::BIT_FLOAT) !== 0; - } - if ($value === null) { - return ($mask & self::BIT_NULL) !== 0; - } - if (\is_array($value)) { - return ($mask & self::BIT_ARRAY) !== 0; - } - - return false; - } -} \ No newline at end of file +} diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index b1b4270d..15849aaf 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -29,27 +29,27 @@ */ final class MemberAssignChecker { - private const OP_NONE = 0; - private const OP_INT = 1; - private const OP_STRING = 2; - private const OP_BOOL = 3; - private const OP_FLOAT = 4; - private const OP_POSITIVE_INT = 5; - private const OP_NON_EMPTY_STRING = 6; - private const OP_ARRAY_KEY = 7; - private const OP_ARRAY = 8; - private const OP_OBJECT = 9; - private const OP_CLASS = 10; - private const OP_MASK = 11; - private const OP_FALLBACK = 12; - - private const BIT_INT = 1; - private const BIT_STRING = 2; - private const BIT_BOOL = 4; - private const BIT_FLOAT = 8; - private const BIT_OBJECT = 16; - private const BIT_NULL = 32; - private const BIT_ARRAY = 64; + public const OP_NONE = 0; + public const OP_INT = 1; + public const OP_STRING = 2; + public const OP_BOOL = 3; + public const OP_FLOAT = 4; + public const OP_POSITIVE_INT = 5; + public const OP_NON_EMPTY_STRING = 6; + public const OP_ARRAY_KEY = 7; + public const OP_ARRAY = 8; + public const OP_OBJECT = 9; + public const OP_CLASS = 10; + public const OP_MASK = 11; + public const OP_FALLBACK = 12; + + public const BIT_INT = 1; + public const BIT_STRING = 2; + public const BIT_BOOL = 4; + public const BIT_FLOAT = 8; + public const BIT_OBJECT = 16; + public const BIT_NULL = 32; + public const BIT_ARRAY = 64; /** * In-memory 2D cache for ReflectionProperty instances: @@ -97,10 +97,10 @@ final class MemberAssignChecker private static array $substitutedElementContractCache = []; /** - * Per-instance contract cache keyed by object identity and global bindings version. + * Per-instance contract cache keyed by object identity and raw instance bindings. * * @var WeakMap, * contracts: array array{0: ?array, 1: array} + * + * @var WeakMap, 1: array}>|null + */ + public static ?WeakMap $fastObjectContractCache = null; + /** * Resets the cached reflection property and element contract registries. */ @@ -124,6 +132,7 @@ public static function reset(): void self::$propertyMutationPlanCache = []; self::$substitutedElementContractCache = []; self::$instanceContractCache = null; + self::$fastObjectContractCache = null; } /** @@ -230,6 +239,9 @@ public static function checkProperty( && \is_object($objectOrClass) ) { $contract = null; + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$objectOrClass] ?? null) + : null; if ($propPlan['usesTemplates']) { self::$instanceContractCache ??= new WeakMap(); @@ -237,12 +249,15 @@ public static function checkProperty( if ( $entry !== null - && $entry['version'] === TemplateManager::$instanceBindingsVersion + && $entry['rawBindings'] === $rawBindings && \array_key_exists($propName, $entry['contracts']) ) { $contract = $entry['contracts'][$propName]; } else { $contract = self::resolveElementContractFromPlan($objectOrClass, $className, $propName, $propPlan); + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$objectOrClass] ?? null) + : null; } } elseif (isset(self::$substitutedElementContractCache[$className][$propName]) && \array_key_exists('', self::$substitutedElementContractCache[$className][$propName])) { $contract = self::$substitutedElementContractCache[$className][$propName]['']; @@ -250,6 +265,18 @@ public static function checkProperty( $contract = self::resolveElementContractFromPlan($objectOrClass, $className, $propName, $propPlan); } + if ($contract !== null) { + self::$fastObjectContractCache ??= new WeakMap(); + $fastEntry = self::$fastObjectContractCache[$objectOrClass] ?? null; + $packed = [$contract['isList'], $contract['keyOp'], $contract['keyExtra'], $contract['valOp'], $contract['valExtra']]; + if ($fastEntry === null || $fastEntry[0] !== $rawBindings) { + self::$fastObjectContractCache[$objectOrClass] = [$rawBindings, [$propName => $packed]]; + } else { + $fastEntry[1][$propName] = $packed; + self::$fastObjectContractCache[$objectOrClass] = $fastEntry; + } + } + $key = $chain[0][1]; if ($contract !== null && (! $contract['isList'] || $key === null)) { $keyOk = true; @@ -560,22 +587,27 @@ private static function resolveElementContractFromPlan( ): ?array { $boundTemplates = []; $useInstanceCache = $propPlan['usesTemplates'] && \is_object($objectOrClass); - $currentVersion = TemplateManager::$instanceBindingsVersion; + $rawBindings = null; if ($useInstanceCache) { self::$instanceContractCache ??= new WeakMap(); $entry = self::$instanceContractCache[$objectOrClass] ?? null; + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$objectOrClass] ?? null) + : null; if ( $entry !== null - && $entry['version'] === $currentVersion + && $entry['rawBindings'] === $rawBindings && \array_key_exists($propName, $entry['contracts']) ) { return $entry['contracts'][$propName]; } $boundTemplates = $preFetchedBindings ?? TemplateManager::getInstanceBindingsFast($objectOrClass); - $currentVersion = TemplateManager::$instanceBindingsVersion; + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$objectOrClass] ?? null) + : null; } $sig = ''; @@ -599,9 +631,9 @@ private static function resolveElementContractFromPlan( if ($useInstanceCache) { $entry = self::$instanceContractCache[$objectOrClass] ?? null; - if ($entry === null || $entry['version'] !== $currentVersion) { + if ($entry === null || $entry['rawBindings'] !== $rawBindings) { self::$instanceContractCache[$objectOrClass] = [ - 'version' => $currentVersion, + 'rawBindings' => $rawBindings, 'contracts' => [$propName => $contract], ]; } else { @@ -790,4 +822,4 @@ private static function getReflectionProperty(string $className, string $propNam return self::$refPropertyCache[$className][$propName] = null; } -} \ No newline at end of file +} diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index e0992f4d..043f3b4e 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -149,6 +149,14 @@ final class ParamChecker */ private static array $paramDynamicCache = []; + /** + * Pre-resolved bound plans for template initial bindings: + * [$function][$templateName] => array{hasTemplateRef: bool, isDynamic: bool, hasConst: bool, resolvedBound: TypeNode, mask: int} + * + * @var array> + */ + private static array $templateBoundPlanCache = []; + /** * Resets internal caches. Useful for test isolation. */ @@ -165,6 +173,7 @@ public static function reset(): void self::$traversablePlanCache = []; self::$callableNodesCache = []; self::$paramDynamicCache = []; + self::$templateBoundPlanCache = []; } /** @@ -294,7 +303,9 @@ public static function checkParams( $registry, $classTemplates, $thisOrClass, - $sensitiveParams + $sensitiveParams, + $hasMethodTemplates, + $functionKind === self::KIND_CONSTRUCT ); } @@ -462,6 +473,10 @@ private static function resolveBaseTypes( array $aliases, bool $paramsAreDynamic = false ): array { + if (! $paramsAreDynamic && isset(self::$baseTypeCache[$effectiveFunction]) && \count(self::$baseTypeCache[$effectiveFunction]) === \count($types)) { + return self::$baseTypeCache[$effectiveFunction]; + } + $baseTypes = []; foreach ($types as $paramName => $typeNode) { if ($paramsAreDynamic && ! isset(self::$paramDynamicCache[$effectiveFunction][$paramName])) { @@ -520,7 +535,9 @@ private static function validateAllParameters( TypeValidatorRegistry $registry, array $classTemplates, object|string|null $thisOrClass = null, - array $sensitiveParams = [] + array $sensitiveParams = [], + bool $hasMethodTemplates = false, + bool $isConstructor = false ): ?ErrorMessage { foreach ($contractTypes as $paramName => $_) { if (! isset($vars[$paramName]) && ! \array_key_exists($paramName, $vars)) { @@ -528,7 +545,9 @@ private static function validateAllParameters( } $currentBoundTemplates = (\count($allTemplates) > 0) - ? TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates) + ? (($thisObj !== null && ! $hasMethodTemplates && ! $isConstructor) + ? TemplateManager::getInstanceBindingsFast($thisObj) + : TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates)) : $boundTemplates; $isSensitive = $sensitiveParams[$paramName] ?? false; @@ -2015,6 +2034,10 @@ private static function validateSingleParam( object|string|null $thisOrClass = null, bool $isSensitive = false ): ?ErrorMessage { + if ($typeNode instanceof IdentifierTypeNode && isset($templates[$typeNode->name])) { + return self::resolveTemplateParam($typeNode, $val, $paramName, $effectiveFunction, $thisObj, $templates, $registry, $classTemplates, $thisOrClass); + } + if (ConditionalChecker::containsConditional($typeNode)) { $typeNode = ConditionalChecker::resolve($typeNode, $vars, $boundTemplates, $registry, $effectiveFunction); } @@ -2391,23 +2414,65 @@ private static function bindInitialTemplate( $inferredType = TemplateManager::inferTypeFromValue($sampleVal); if ($templateNode->bound !== null) { - $boundNode = $templateNode->bound; - $currentBindings = TemplateManager::getBoundTemplates($function, $thisObj, $templates); - $allBindings = [...$currentBindings, $templateName => $inferredType]; + $bPlan = self::$templateBoundPlanCache[$function][$templateName] ?? null; + if ($bPlan === null) { + $rawBound = $templateNode->bound; + $hasTemplateRef = TemplateManager::isFBounded($templateNode, $function) + || DocblockParser::typeReferencesTemplate($rawBound, $templates); + $boundStr = (string) $rawBound; + $isDynamic = str_contains($boundStr, 'static') || str_contains($boundStr, '$this'); + $resolvedBound = (! $hasTemplateRef && ! $isDynamic) + ? SpecialTypeResolver::resolve($rawBound, $function, null) + : $rawBound; + + $bPlan = self::$templateBoundPlanCache[$function][$templateName] = [ + 'hasTemplateRef' => $hasTemplateRef, + 'isDynamic' => $isDynamic, + 'hasConst' => self::typeContainsConst($resolvedBound), + 'resolvedBound' => $resolvedBound, + 'mask' => (! $hasTemplateRef && ! $isDynamic) ? self::compilePrimitiveBoundMask($resolvedBound) : 0, + ]; + } + + if (! $bPlan['hasTemplateRef'] && ! $bPlan['isDynamic']) { + $resolvedBound = $bPlan['resolvedBound']; + if ($bPlan['hasConst']) { + $inferredType = self::refineInferredTypeFromBound($sampleVal, $resolvedBound, $inferredType); + } - if ( - TemplateManager::isFBounded($templateNode, $function) - || DocblockParser::typeReferencesTemplate($boundNode, $templates) - ) { - $boundNode = TemplateSubstitutor::substitute($boundNode, $allBindings); - } + $mask = $bPlan['mask']; + $fastOk = $mask !== 0 && ( + (\is_string($sampleVal) && ($mask & 2) !== 0) + || (\is_int($sampleVal) && ($mask & 9) !== 0) + || (\is_object($sampleVal) && ($mask & 16) !== 0) + || (\is_bool($sampleVal) && ($mask & 4) !== 0) + || (\is_float($sampleVal) && ($mask & 8) !== 0) + || ($sampleVal === null && ($mask & 32) !== 0) + || (\is_array($sampleVal) && ($mask & 64) !== 0) + ); - $resolvedBound = SpecialTypeResolver::resolve($boundNode, $function, $thisObj); - $inferredType = self::refineInferredTypeFromBound($sampleVal, $resolvedBound, $inferredType); + if (! $fastOk) { + $err = $registry->validate($sampleVal, $resolvedBound, $function . '(): Argument $' . $paramName . ' (template ' . $templateName . ')'); + if ($err !== null) { + return $err; + } + } + } else { + $boundNode = $templateNode->bound; + $currentBindings = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + $allBindings = [...$currentBindings, $templateName => $inferredType]; - $err = $registry->validate($sampleVal, $resolvedBound, $function . '(): Argument $' . $paramName . ' (template ' . $templateName . ')'); - if ($err !== null) { - return $err; + if ($bPlan['hasTemplateRef']) { + $boundNode = TemplateSubstitutor::substitute($boundNode, $allBindings); + } + + $resolvedBound = SpecialTypeResolver::resolve($boundNode, $function, $thisObj); + $inferredType = self::refineInferredTypeFromBound($sampleVal, $resolvedBound, $inferredType); + + $err = $registry->validate($sampleVal, $resolvedBound, $function . '(): Argument $' . $paramName . ' (template ' . $templateName . ')'); + if ($err !== null) { + return $err; + } } } @@ -2431,6 +2496,58 @@ private static function bindInitialTemplate( return null; } + private static function typeContainsConst(TypeNode $node): bool + { + if ($node instanceof \PHPStan\PhpDocParser\Ast\Type\ConstTypeNode) { + return true; + } + + if ($node instanceof UnionTypeNode) { + foreach ($node->types as $member) { + if (self::typeContainsConst($member)) { + return true; + } + } + } + + return false; + } + + private static function compilePrimitiveBoundMask(TypeNode $node): int + { + if ($node instanceof IdentifierTypeNode) { + return match (strtolower($node->name)) { + 'int', 'integer' => 1, + 'string' => 2, + 'bool', 'boolean' => 4, + 'float', 'double' => 8, + 'object' => 16, + 'null' => 32, + 'array' => 64, + 'array-key' => 3, + default => 0, + }; + } + + if ($node instanceof UnionTypeNode) { + $mask = 0; + foreach ($node->types as $member) { + if (! ($member instanceof IdentifierTypeNode)) { + return 0; + } + $bit = self::compilePrimitiveBoundMask($member); + if ($bit === 0) { + return 0; + } + $mask |= $bit; + } + + return $mask; + } + + return 0; + } + private static function validateBoundTemplate( mixed $val, string $paramName, diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index dd29c632..f5546f49 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -382,7 +382,9 @@ private static function evaluateReturn( return $value; } - $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + $boundTemplates = ($thisObj !== null && ($contract['templates'] ?? []) === []) + ? TemplateManager::getInstanceBindingsFast($thisObj) + : TemplateManager::getBoundTemplates($function, $thisObj, $templates); $isDynamicReturn = $contract['returnIsDynamic'] ?? (str_contains((string) $returnTypeNode, 'static') || str_contains((string) $returnTypeNode, '$this')); diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index dd8b1beb..0711e2e1 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -49,7 +49,7 @@ final class TemplateManager * * @var WeakMap>|null */ - private static ?WeakMap $instanceTemplateBindings = null; + public static ?WeakMap $instanceTemplateBindings = null; /** * Call stack frames storing template bindings per function or method call. @@ -120,9 +120,9 @@ final class TemplateManager public static ?object $pendingCloneSource = null; /** - * Monotonic version bumped whenever any instance's template bindings are written. + * Fast boolean flag indicating whether any pending constructor generic instantiations are active. */ - public static int $instanceBindingsVersion = 0; + public static bool $hasPendingInstantiations = false; /** * Fast O(1) hashmap for recognized key template names. @@ -378,13 +378,13 @@ final class TemplateManager 'scalar' => true, ]; - private static ?IdentifierTypeNode $intNode = null; + public static ?IdentifierTypeNode $intNode = null; - private static ?IdentifierTypeNode $stringNode = null; + public static ?IdentifierTypeNode $stringNode = null; - private static ?IdentifierTypeNode $floatNode = null; + public static ?IdentifierTypeNode $floatNode = null; - private static ?IdentifierTypeNode $boolNode = null; + public static ?IdentifierTypeNode $boolNode = null; private static ?IdentifierTypeNode $listNode = null; @@ -498,6 +498,7 @@ final class TemplateManager * templateList?: list, * normalizedTypeArgs?: array, * hasPropagation?: bool, + * allStaticValid?: bool, * items?: list * }> * }>|null */ @@ -523,6 +525,7 @@ final class TemplateManager * templateList: list, * normalizedTypeArgs: array, * hasPropagation: bool, + * allStaticValid: bool, * items: list * }> * }>>|null */ private static ?WeakMap $compiledRelativeNodeBindPlanCache = null; + /** + * @var WeakMap, hasObject: bool}>|null + */ + private static ?WeakMap $compiledUnionMembersCache = null; + /** * Fast O(1) cache of class names known to have zero inherited generic bindings or raw mappings. * @@ -573,7 +582,7 @@ public static function reset(): void self::$subclassCache = []; self::$realTypeSymbolCache = []; self::$pendingCloneSource = null; - self::$instanceBindingsVersion = 0; + self::$hasPendingInstantiations = false; self::$methodTemplatesCache = []; self::$isMethodTemplateCache = []; self::$isFBoundCache = []; @@ -587,6 +596,7 @@ public static function reset(): void self::$propagationPlanCache = []; self::$compiledNodeBindPlanCache = null; self::$compiledRelativeNodeBindPlanCache = null; + self::$compiledUnionMembersCache = null; self::$noInheritedBindingsClasses = []; } @@ -604,8 +614,6 @@ public static function restoreInstanceBindings(object $instance, array $bindings } else { self::$instanceTemplateBindings[$instance] = $bindings; } - - self::$instanceBindingsVersion++; } /** @@ -635,6 +643,7 @@ public static function pushPendingInstantiation(string $typeString, string $file 'file' => $file, 'targetClass' => $targetClass, ]; + self::$hasPendingInstantiations = true; } /** @@ -643,6 +652,7 @@ public static function pushPendingInstantiation(string $typeString, string $file public static function popPendingInstantiation(): void { array_pop(self::$pendingInstantiations); + self::$hasPendingInstantiations = (self::$pendingInstantiations !== []); } /** @@ -650,7 +660,7 @@ public static function popPendingInstantiation(): void */ public static function applyPendingInstantiation(object $instance): void { - if (! Config::isInlineGenericsEnabled() || self::$pendingInstantiations === []) { + if (! self::$hasPendingInstantiations || ! Config::isInlineGenericsEnabled()) { return; } @@ -702,7 +712,7 @@ public static function getClassInheritedBindings(string $className): array return self::$classInheritedBindingsCache[$className]; } - if (! class_exists($className, false) && ! class_exists($className) && ! interface_exists($className) && ! trait_exists($className)) { + if (! class_exists($className, false) && ! class_exists($className) && ! interface_exists($className, false) && ! trait_exists($className)) { return self::$classInheritedBindingsCache[$className] = []; } @@ -778,7 +788,6 @@ public static function copyInstanceBindings(object $source, object $target): voi $bindings = self::$instanceTemplateBindings[$source]; $bindings = self::widenClonedBindingsFromActiveCall($target, $bindings); self::$instanceTemplateBindings[$target] = $bindings; - self::$instanceBindingsVersion++; } if (self::isGeneratorInferred($source)) { @@ -913,12 +922,13 @@ public static function getBoundTemplates(string $function, object|string|null $t $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; if ($thisObj !== null) { - self::ensureInstanceInherited($thisObj); - $isCtor = str_ends_with(strtolower($function), '::__construct'); - $bindings = $isCtor - ? (self::$instanceTemplateBindings[$thisObj] ?? []) - : self::getBoundTemplatesForInstance($thisObj); + if ($isCtor) { + self::ensureInstanceInherited($thisObj); + $bindings = self::$instanceTemplateBindings[$thisObj] ?? []; + } else { + $bindings = self::getInstanceBindingsFast($thisObj); + } $methodTemplates = self::getMethodTemplates($function); if ($methodTemplates !== []) { @@ -1204,7 +1214,6 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ } self::$instanceTemplateBindings[$thisObj] = $bindings; - self::$instanceBindingsVersion++; } else { if (! self::hasCallFrame($function)) { self::$callStackBindings[$function][] = []; @@ -1270,23 +1279,13 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t if ( $existingBindings !== null + && $plan['allStaticValid'] && ! $forceBind && ! $refineOnly - && self::$generatorInferredCallFrames === [] ) { $allFastMatched = true; foreach ($plan['items'] as $item) { - if (! $item['symbolValid']) { - continue; - } - - if (! $item['boundSatisfied']) { - $allFastMatched = false; - - break; - } - $tName = $item['name']; if (! isset($existingBindings[$tName])) { $allFastMatched = false; @@ -1313,6 +1312,14 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t continue; } + if ( + $item['unionNames'] !== null + && $existingTypeNode instanceof IdentifierTypeNode + && isset($item['unionNames'][$existingTypeNode->name]) + ) { + continue; + } + if ( $existingTypeNode::class === $expectedTypeNode::class && (string) $existingTypeNode === (string) $expectedTypeNode @@ -1326,6 +1333,16 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t } if ($allFastMatched) { + if (self::$generatorInferredCallFrames !== [] && self::$activeCallOrder !== []) { + $activeFunc = end(self::$activeCallOrder); + if ($activeFunc !== false && isset(self::$generatorInferredCallFrames[$activeFunc])) { + self::$generatorInferredInstances ??= new WeakMap(); + if (! isset(self::$generatorInferredInstances[$instance])) { + self::$generatorInferredInstances[$instance] = true; + } + } + } + if ($plan['hasPropagation']) { self::propagateBindingsIfNeeded($instance, $existingBindings); } @@ -1343,7 +1360,9 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t self::$instanceTemplateBindings ??= new WeakMap(); $candidateBindings = self::$instanceTemplateBindings[$instance] ?? []; + $itemsByIndex = []; foreach ($plan['items'] as $item) { + $itemsByIndex[$item['index']] = $item; if (! $item['isWildcardOrMixed']) { $candidateBindings[$item['name']] = $item['expected']; } @@ -1354,6 +1373,8 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t continue; } + $planItem = $itemsByIndex[$index] ?? null; + $err = self::bindSingleTemplateArgument( $instance, $className, @@ -1364,7 +1385,9 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t $context, $forceBind, $candidateBindings, - $refineOnly + $refineOnly, + $planItem !== null && $planItem['symbolValid'], + $planItem !== null && $planItem['boundSatisfied'] ); if ($err !== null) { return $err; @@ -1394,6 +1417,7 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t * templateList: list, * normalizedTypeArgs: array, * hasPropagation: bool, + * allStaticValid: bool, * items: list * }> * } */ @@ -1417,6 +1442,7 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str 'templateList' => [], 'normalizedTypeArgs' => [], 'hasPropagation' => false, + 'allStaticValid' => false, 'items' => [], ]; } @@ -1427,6 +1453,7 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str $normalizedTypeArgs = self::normalizeGenericArguments($typeNode->genericTypes, $templateList); $hasPropagation = self::propagationPlan($className) !== []; $items = []; + $allStaticValid = true; foreach ($templateList as $index => $templateTag) { if (! isset($normalizedTypeArgs[$index])) { @@ -1459,15 +1486,39 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str } } + if (! $symbolValid || ! $boundSatisfied) { + $allStaticValid = false; + } + + $declaredVar = $classVariances[$templateTag->name] ?? GenericTypeNode::VARIANCE_INVARIANT; + $usageVar = $typeNode->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT; + $unionNames = null; + if ( + $expectedTypeNode instanceof UnionTypeNode + && $declaredVar !== GenericTypeNode::VARIANCE_CONTRAVARIANT + && $usageVar !== GenericTypeNode::VARIANCE_CONTRAVARIANT + ) { + $uNames = []; + foreach ($expectedTypeNode->types as $uMember) { + if ($uMember instanceof IdentifierTypeNode) { + $uNames[$uMember->name] = true; + } + } + if ($uNames !== []) { + $unionNames = $uNames; + } + } + $items[] = [ 'index' => $index, 'name' => $templateTag->name, 'expected' => $expectedTypeNode, 'identName' => $identName, - 'usageVariance' => $typeNode->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT, + 'usageVariance' => $usageVar, 'isWildcardOrMixed' => $isWildcardOrMixed, 'symbolValid' => $symbolValid, 'boundSatisfied' => $boundSatisfied, + 'unionNames' => $unionNames, ]; } @@ -1479,6 +1530,7 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str 'templateList' => $templateList, 'normalizedTypeArgs' => $normalizedTypeArgs, 'hasPropagation' => $hasPropagation, + 'allStaticValid' => $allStaticValid, 'items' => $items, ]; } catch (\Throwable) { @@ -1490,6 +1542,7 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str 'templateList' => [], 'normalizedTypeArgs' => [], 'hasPropagation' => false, + 'allStaticValid' => false, 'items' => [], ]; } @@ -1542,7 +1595,6 @@ public static function applyClassTemplateDefaults(object $instance, array $class if ($changed) { self::$instanceTemplateBindings[$instance] = $bindings; - self::$instanceBindingsVersion++; } } @@ -1946,31 +1998,35 @@ private static function bindSingleTemplateArgument( string $context, bool $forceBind, array $candidateBindings = [], - bool $refineOnly = false + bool $refineOnly = false, + bool $symbolPreVerified = false, + bool $boundPreVerified = false ): ?ErrorMessage { - if ($expectedTypeNode instanceof IdentifierTypeNode) { - if (str_contains($expectedTypeNode->name, '::')) { - $targetClass = explode('::', $expectedTypeNode->name, 2)[0]; - if (! self::isRealTypeSymbol($targetClass)) { - return null; - } - } else { - $isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($expectedTypeNode->name); - $isRealType = self::isRealTypeSymbol($expectedTypeNode->name); + if (! $symbolPreVerified) { + if ($expectedTypeNode instanceof IdentifierTypeNode) { + if (str_contains($expectedTypeNode->name, '::')) { + $targetClass = explode('::', $expectedTypeNode->name, 2)[0]; + if (! self::isRealTypeSymbol($targetClass)) { + return null; + } + } else { + $isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($expectedTypeNode->name); + $isRealType = self::isRealTypeSymbol($expectedTypeNode->name); - if (! $isBuiltIn && ! $isRealType) { + if (! $isBuiltIn && ! $isRealType) { + return null; + } + } + } elseif ($expectedTypeNode instanceof ConstTypeNode && $expectedTypeNode->constExpr instanceof ConstFetchNode && $expectedTypeNode->constExpr->className !== '') { + if (! self::isRealTypeSymbol($expectedTypeNode->constExpr->className)) { return null; } } - } elseif ($expectedTypeNode instanceof ConstTypeNode && $expectedTypeNode->constExpr instanceof ConstFetchNode && $expectedTypeNode->constExpr->className !== '') { - if (! self::isRealTypeSymbol($expectedTypeNode->constExpr->className)) { - return null; - } } $isWildcardOrMixed = ($expectedTypeNode instanceof IdentifierTypeNode && ($expectedTypeNode->name === '*' || strtolower($expectedTypeNode->name) === 'mixed')); - if ($templateTag->bound !== null && ! $isWildcardOrMixed) { + if (! $boundPreVerified && $templateTag->bound !== null && ! $isWildcardOrMixed) { $boundNode = $templateTag->bound; $allBindings = [...$candidateBindings, $templateTag->name => $expectedTypeNode]; if (self::isFBounded($templateTag, $className) || DocblockParser::typeReferencesTemplate($boundNode, $allBindings)) { @@ -2028,7 +2084,6 @@ private static function bindSingleTemplateArgument( } self::$instanceTemplateBindings[$instance] = $bindings; - self::$instanceBindingsVersion++; if ($isReturnContext && self::isGeneratorInferred($instance)) { self::propagateGeneratorRefinementToProperties($instance, $templateName, $expectedTypeNode); @@ -2046,7 +2101,6 @@ private static function bindSingleTemplateArgument( $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; self::$instanceTemplateBindings[$instance] = $bindings; - self::$instanceBindingsVersion++; return null; } @@ -2063,7 +2117,6 @@ private static function bindSingleTemplateArgument( $bindings = self::$instanceTemplateBindings[$instance] ?? []; $bindings[$templateName] = $expectedTypeNode; self::$instanceTemplateBindings[$instance] = $bindings; - self::$instanceBindingsVersion++; return null; } @@ -2104,7 +2157,6 @@ private static function bindSingleTemplateArgument( } $map[$instance] = $bindings; - self::$instanceBindingsVersion++; } return null; @@ -2144,7 +2196,6 @@ private static function propagateGeneratorRefinementToProperties(object $instanc } } $map[$propVal] = $propBindings; - self::$instanceBindingsVersion++; } } } catch (\Throwable) { @@ -2305,7 +2356,6 @@ public static function resolveInheritedTemplates(object $instance, string $targe if ($existing === []) { if ($cachedBindings !== []) { self::$instanceTemplateBindings[$instance] = $cachedBindings; - self::$instanceBindingsVersion++; } return; @@ -2330,7 +2380,6 @@ public static function resolveInheritedTemplates(object $instance, string $targe $merged = [...$existing, ...$specializedBindings]; if ($merged !== [] && $merged !== $existing) { self::$instanceTemplateBindings[$instance] = $merged; - self::$instanceBindingsVersion++; } } @@ -2575,7 +2624,7 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return true; } - if (self::isScalarSubtype($lowerExisting, $lowerExpected)) { + if (isset(self::SCALAR_SUBTYPES[$lowerExpected][$lowerExisting]) || self::isScalarSubtype($lowerExisting, $lowerExpected)) { return true; } @@ -2906,6 +2955,37 @@ private static function checkExpectedUnionVariance(TypeNode $existing, UnionType return true; } + if ($existing instanceof IdentifierTypeNode) { + self::$compiledUnionMembersCache ??= new WeakMap(); + $compiled = self::$compiledUnionMembersCache[$expected] ?? null; + if ($compiled === null) { + $names = []; + $hasObject = false; + foreach ($expected->types as $uType) { + if ($uType instanceof IdentifierTypeNode) { + $lower = strtolower($uType->name); + $names[$uType->name] = true; + $names[$lower] = true; + if ($lower === 'object') { + $hasObject = true; + } + } + } + self::$compiledUnionMembersCache[$expected] = $compiled = [ + 'names' => $names, + 'hasObject' => $hasObject, + ]; + } + + if (isset($compiled['names'][$existing->name])) { + return true; + } + + if ($compiled['hasObject'] && ClassNameValidator::isValid($existing->name) && self::isRealTypeSymbol($existing->name)) { + return true; + } + } + if ($existing instanceof UnionTypeNode) { foreach ($existing->types as $existingVariant) { if (! self::checkExpectedUnionVariance($existingVariant, $expected, $variance)) { @@ -3500,4 +3580,4 @@ private static function resolveTypeNodeAst(TypeNode $n, \ReflectionClass $ref): return $n; } -} \ No newline at end of file +} diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index d5223544..7a418349 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -5,9 +5,11 @@ namespace TypePHP\Internal; use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use PHPStan\PhpDocParser\Parser\TokenIterator; use Traversable; use TypePHP\Internal\Ast\ScopeCleaner; @@ -93,12 +95,17 @@ final class RuntimeTypeChecker private static ?TypeValidatorRegistry $registry = null; /** - * @var array}> + * @var array}> */ private static array $simpleScopePlanCache = []; /** - * @var array + * @var array}> + */ + private static array $simpleCtorTemplatePlanCache = []; + + /** + * @var array */ private static array $simpleReturnPlanCache = []; @@ -125,6 +132,7 @@ final class RuntimeTypeChecker public static function reset(): void { self::$simpleScopePlanCache = []; + self::$simpleCtorTemplatePlanCache = []; self::$simpleReturnPlanCache = []; self::$genericReturnPlanCache = []; self::$hasMethodTemplatesCache = []; @@ -295,6 +303,85 @@ public static function checkPropertyMemberAssign( return $value; } + if ( + self::$arrayValidationHybrid + && \is_object($objectOrClass) + && MemberAssignChecker::$fastObjectContractCache !== null + && isset($chain[0]) && ! isset($chain[1]) && $chain[0][0] === 'dim' + ) { + $entry = MemberAssignChecker::$fastObjectContractCache[$objectOrClass] ?? null; + if ($entry !== null && isset($entry[1][$propName])) { + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$objectOrClass] ?? null) + : null; + + if ($entry[0] === $rawBindings) { + $c = $entry[1][$propName]; // [0 => isList, 1 => keyOp, 2 => keyExtra, 3 => valOp, 4 => valExtra] + $key = $chain[0][1]; + + if (! $c[0] || $key === null) { + $keyOk = true; + if (! $c[0] && $key !== null && $c[1] !== MemberAssignChecker::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_string($key) && (((int) $kExtra) & MemberAssignChecker::BIT_STRING) !== 0) + || (\is_int($key) && (((int) $kExtra) & (MemberAssignChecker::BIT_INT | MemberAssignChecker::BIT_FLOAT)) !== 0) + || (\is_object($key) && (((int) $kExtra) & MemberAssignChecker::BIT_OBJECT) !== 0) + || (\is_bool($key) && (((int) $kExtra) & MemberAssignChecker::BIT_BOOL) !== 0) + || (\is_float($key) && (((int) $kExtra) & MemberAssignChecker::BIT_FLOAT) !== 0) + || (\is_array($key) && (((int) $kExtra) & MemberAssignChecker::BIT_ARRAY) !== 0) + ), + MemberAssignChecker::OP_OBJECT => \is_object($key), + MemberAssignChecker::OP_CLASS => \is_object($key) && ($key instanceof $kExtra), + default => false, + }; + } + + if ($keyOk) { + $vOp = $c[3]; + if ($vOp === MemberAssignChecker::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) && ($value instanceof $vExtra), + MemberAssignChecker::OP_MASK => ( + (\is_string($value) && (((int) $vExtra) & MemberAssignChecker::BIT_STRING) !== 0) + || (\is_int($value) && (((int) $vExtra) & (MemberAssignChecker::BIT_INT | MemberAssignChecker::BIT_FLOAT)) !== 0) + || (\is_object($value) && (((int) $vExtra) & MemberAssignChecker::BIT_OBJECT) !== 0) + || (\is_bool($value) && (((int) $vExtra) & MemberAssignChecker::BIT_BOOL) !== 0) + || (\is_float($value) && (((int) $vExtra) & MemberAssignChecker::BIT_FLOAT) !== 0) + || ($value === null && (((int) $vExtra) & MemberAssignChecker::BIT_NULL) !== 0) + || (\is_array($value) && (((int) $vExtra) & MemberAssignChecker::BIT_ARRAY) !== 0) + ), + default => false, + }; + + if ($valOk) { + return $value; + } + } + } + } + } + } + $res = MemberAssignChecker::checkProperty( $objectOrClass, $propName, @@ -521,6 +608,66 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } + if ( + isset(self::$simpleCtorTemplatePlanCache[$function]) + && \is_object($thisOrClass) + && ! TemplateManager::$hasPendingInstantiations + && (TemplateManager::$instanceTemplateBindings === null || ! isset(TemplateManager::$instanceTemplateBindings[$thisOrClass])) + ) { + $ctorPlan = self::$simpleCtorTemplatePlanCache[$function]; + if ($thisOrClass::class === $ctorPlan['class']) { + $bindings = []; + $fastValid = true; + + foreach ($ctorPlan['items'] as $item) { + $paramName = $item[0]; + if (isset($vars[$paramName])) { + $val = $vars[$paramName]; + } elseif (\array_key_exists($paramName, $vars)) { + $val = null; + } else { + $fastValid = false; + + break; + } + + $mask = $item[2]; + if ($mask !== 0) { + $ok = ( + (\is_string($val) && ($mask & 2) !== 0) + || (\is_int($val) && ($mask & 9) !== 0) + || (\is_object($val) && ($mask & 16) !== 0) + || (\is_bool($val) && ($mask & 4) !== 0) + || (\is_float($val) && ($mask & 8) !== 0) + || ($val === null && ($mask & 32) !== 0) + || (\is_array($val) && ($mask & 64) !== 0) + ); + if (! $ok) { + $fastValid = false; + + break; + } + } + + $tName = $item[1]; + if (\is_string($val)) { + $bindings[$tName] = TemplateManager::$stringNode ??= new IdentifierTypeNode('string'); + } elseif (\is_int($val)) { + $bindings[$tName] = TemplateManager::$intNode ??= new IdentifierTypeNode('int'); + } else { + $bindings[$tName] = TemplateManager::inferTypeFromValue($val); + } + } + + if ($fastValid) { + TemplateManager::$instanceTemplateBindings ??= new \WeakMap(); + TemplateManager::$instanceTemplateBindings[$thisOrClass] = $bindings; + + return null; + } + } + } + $plan = self::$simpleScopePlanCache[$function] ?? null; if ( @@ -577,6 +724,33 @@ public static function setupScope(string $function, array $vars, object|string|n $registry = self::$registry ??= new TypeValidatorRegistry(); + if ( + $functionKind === ParamChecker::KIND_CONSTRUCT + && $thisObj !== null + && $effectiveFunction === $function + && ! TemplateManager::$hasPendingInstantiations + && $contract['templates'] === [] + && $contract['classTemplates'] !== [] + && $contract['aliases'] === [] + && ! $contract['paramsAreDynamic'] + && ($contract['paramConditionals'] ?? []) === [] + && ! ($contract['hasCrossReferencedBounds'] ?? false) + && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) + && TemplateManager::getClassInheritedBindings($thisObj::class) === [] + ) { + $ctorPlanItems = self::compileSimpleCtorTemplatePlanItems( + $contract['types'], + $contract['classTemplates'], + $effectiveFunction + ); + if ($ctorPlanItems !== null) { + self::$simpleCtorTemplatePlanCache[$effectiveFunction] = [ + 'class' => $thisObj::class, + 'items' => $ctorPlanItems, + ]; + } + } + $paramsAreSimple = $contract['paramsAreSimple'] ?? $contract['isSimple']; if ( ! $isMagicCall @@ -672,6 +846,121 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } + /** + * Compiles a simple constructor parameter-to-template plan when all parameters are distinct bare class templates + * with no defaults or complex/const bounds. Returns null if the constructor is not eligible. + * + * @param array $types + * @param array $classTemplates + * + * @return list|null + */ + private static function compileSimpleCtorTemplatePlanItems(array $types, array $classTemplates, string $effectiveFunction): ?array + { + if ($types === []) { + return null; + } + + foreach ($classTemplates as $tTag) { + if ($tTag->default !== null && ! TemplateManager::isUnspecializedDefault($tTag)) { + return null; + } + } + + $seenTemplates = []; + $items = []; + + foreach ($types as $paramName => $typeNode) { + if (! ($typeNode instanceof IdentifierTypeNode) || ! isset($classTemplates[$typeNode->name])) { + return null; + } + + $tName = $typeNode->name; + if (isset($seenTemplates[$tName])) { + return null; + } + $seenTemplates[$tName] = true; + + $tTag = $classTemplates[$tName]; + $mask = 0; + if ($tTag->bound !== null) { + $boundStr = (string) $tTag->bound; + if (str_contains($boundStr, 'static') || str_contains($boundStr, '$this')) { + return null; + } + if (DocblockParser::typeReferencesTemplate($tTag->bound, $classTemplates)) { + return null; + } + + $resolvedBound = SpecialTypeResolver::resolve($tTag->bound, $effectiveFunction, null); + if (self::typeNodeContainsConst($resolvedBound)) { + return null; + } + + $mask = self::compilePrimitiveBoundMask($resolvedBound); + if ($mask === 0) { + return null; + } + } + + $items[] = [$paramName, $tName, $mask]; + } + + return $items; + } + + private static function typeNodeContainsConst(TypeNode $node): bool + { + if ($node instanceof ConstTypeNode) { + return true; + } + + if ($node instanceof UnionTypeNode) { + foreach ($node->types as $member) { + if (self::typeNodeContainsConst($member)) { + return true; + } + } + } + + return false; + } + + private static function compilePrimitiveBoundMask(TypeNode $node): int + { + if ($node instanceof IdentifierTypeNode) { + return match (strtolower($node->name)) { + 'int', 'integer' => 1, + 'string' => 2, + 'bool', 'boolean' => 4, + 'float', 'double' => 8, + 'object' => 16, + 'null' => 32, + 'array' => 64, + 'array-key' => 3, + default => 0, + }; + } + + if ($node instanceof UnionTypeNode) { + $mask = 0; + foreach ($node->types as $member) { + if (! ($member instanceof IdentifierTypeNode)) { + return 0; + } + $bit = self::compilePrimitiveBoundMask($member); + if ($bit === 0) { + return 0; + } + $mask |= $bit; + } + + return $mask; + } + + return 0; + } + /** * @param array{class: ?string, requireObject: bool, function: string, items: list} $plan * @param array $vars diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index ca868c79..3fc65c48 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -101,14 +101,14 @@ public function validate(mixed $value, TypeNode $node, string $context = '', boo return $this->identifierValidator->validate($value, $node, $context, $this, $isSensitive); } - if ($node instanceof ArrayShapeNode) { - return $this->arrayShapeValidator->validate($value, $node, $context, $this, $isSensitive); - } - if ($node instanceof GenericTypeNode) { return $this->genericValidator->validate($value, $node, $context, $this, $isSensitive); } + if ($node instanceof ArrayShapeNode) { + return $this->arrayShapeValidator->validate($value, $node, $context, $this, $isSensitive); + } + if ($node instanceof UnionTypeNode) { return $this->unionValidator->validate($value, $node, $context, $this, $isSensitive); } diff --git a/src/Internal/Wrapper/CallableWrapper.php b/src/Internal/Wrapper/CallableWrapper.php index d5c9abb0..ab747f5b 100644 --- a/src/Internal/Wrapper/CallableWrapper.php +++ b/src/Internal/Wrapper/CallableWrapper.php @@ -302,6 +302,117 @@ private static function createDispatcherClosure( } if (! $hasAnyRef) { + if ($typeNode->templateTypes === []) { + $hasVariadic = false; + $paramChecks = []; + foreach ($typeNode->parameters as $idx => $p) { + if ($p->isVariadic) { + $hasVariadic = true; + + break; + } + if ($p->type instanceof IdentifierTypeNode && strtolower($p->type->name) === 'mixed') { + continue; + } + $rawName = ltrim($p->parameterName ?? '', '$'); + $label = $rawName !== '' ? "\$$rawName" : ('argument #' . ($idx + 1)); + $pScalar = $p->type instanceof IdentifierTypeNode ? match (strtolower($p->type->name)) { + 'int', 'integer' => 'int', + 'string' => 'string', + 'bool', 'boolean' => 'bool', + default => null, + } : null; + $paramChecks[] = [$idx, $p->type, $label, $pScalar]; + } + + $retType = $typeNode->returnType; + $isVoidOrMixedReturn = $retType instanceof IdentifierTypeNode + && \in_array(strtolower($retType->name), ['void', 'mixed'], true); + $retIsCallable = $retType instanceof CallableTypeNode; + $retScalar = $retType instanceof IdentifierTypeNode ? match (strtolower($retType->name)) { + 'int', 'integer' => 'int', + 'string' => 'string', + 'bool', 'boolean' => 'bool', + default => null, + } : null; + + if (! $hasVariadic) { + if ($paramChecks === [] && $isVoidOrMixedReturn) { + return $callable instanceof Closure ? $callable : $callable(...); + } + + return function (...$args) use ($callable, $typeNode, $paramChecks, $retType, $isVoidOrMixedReturn, $retIsCallable, $retScalar, $registry, $prefix) { + if ($paramChecks !== []) { + if ($args !== [] && ! array_is_list($args)) { + self::validateCallbackArguments($typeNode, $args, $prefix, $registry, $callable); + } else { + foreach ($paramChecks as $pc) { + $idx = $pc[0]; + if (isset($args[$idx]) || \array_key_exists($idx, $args)) { + $argVal = $args[$idx]; + $pScalar = $pc[3]; + if ( + ($pScalar === 'int' && \is_int($argVal)) + || ($pScalar === 'string' && \is_string($argVal)) + || ($pScalar === 'bool' && \is_bool($argVal)) + ) { + continue; + } + + $err = $registry->validate($argVal, $pc[1], ''); + if ($err !== null) { + if (CallerBoundaryResolver::shouldBypassCallback($callable, $prefix)) { + continue; + } + if (IgnoreManager::isCallerIgnored()) { + continue; + } + $fullErr = ErrorFactory::createError("$prefix {$pc[2]}" . $err->getMessage()); + $handled = ViolationCollector::handle($fullErr, 'callback', null); + if ($handled instanceof ErrorMessage) { + throw ErrorFactory::prepareException(new TypePHPTypeError($fullErr->getMessage())); + } + } + } + } + } + } + + try { + $result = $callable(...$args); + } catch (TypeError $e) { + throw ErrorFactory::prepareException($e); + } + + if ( + ! $isVoidOrMixedReturn + && ! ( + ($retScalar === 'string' && \is_string($result)) + || ($retScalar === 'int' && \is_int($result)) + || ($retScalar === 'bool' && \is_bool($result)) + ) + ) { + $err = $registry->validate($result, $retType, ''); + if ($err !== null) { + if (! CallerBoundaryResolver::shouldBypassCallback($callable, $prefix) && ! IgnoreManager::isCallerIgnored()) { + $fullErr = ErrorFactory::createError("$prefix return value" . $err->getMessage()); + $handled = ViolationCollector::handle($fullErr, 'callback', $result); + if ($handled instanceof ErrorMessage) { + throw ErrorFactory::prepareException(new TypePHPTypeError($fullErr->getMessage())); + } + } + } + } + + if ($retIsCallable && self::isCallable($result)) { + $result = self::wrapTypeNode($retType, $result, "$prefix: Returned callback", $registry); + } + + return $result; + }; + } + } + return function (...$args) use ($callable, $typeNode, $registry, $prefix, $function, $paramName) { $effectiveTypeNode = self::resolveEffectiveCallableTypeNode($typeNode, $args, $prefix, $registry, $callable, $function, $paramName); diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index 71886bc5..0ee9baae 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -295,47 +295,71 @@ private static function createValidationCallback( string $prefix, string $function = '' ): \Closure { - return function (mixed $key, mixed $value) use ($registry, $keyTypeNode, $itemTypeNode, $prefix, $function): void { - if ($keyTypeNode !== null && $key !== null) { - $err = $registry->validate($key, $keyTypeNode, "$prefix key"); - if ($err !== null) { - if ($function !== '' && CallerBoundaryResolver::shouldBypass($function)) { - return; - } - - if (CallerBoundaryResolver::isCallerVendor()) { - return; - } - - if (IgnoreManager::isCallerIgnored()) { - return; - } + $keyName = $keyTypeNode instanceof IdentifierTypeNode ? strtolower($keyTypeNode->name) : null; + if ($keyName === 'mixed' || $keyName === 'array-key') { + $keyTypeNode = null; + } + $valName = $itemTypeNode instanceof IdentifierTypeNode ? strtolower($itemTypeNode->name) : null; + if ($valName === 'mixed') { + $itemTypeNode = null; + } - $handled = ViolationCollector::handle($err, 'yield', null, function: $function); - if ($handled instanceof ErrorMessage) { - throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); + return function (mixed $key, mixed $value) use ($registry, $keyTypeNode, $itemTypeNode, $keyName, $valName, $prefix, $function): void { + if ($keyTypeNode !== null && $key !== null) { + $keyOk = match ($keyName) { + 'int', 'integer' => \is_int($key), + 'string' => \is_string($key), + default => false, + }; + + if (! $keyOk) { + $err = $registry->validate($key, $keyTypeNode, ''); + if ($err !== null) { + if ($function !== '' && CallerBoundaryResolver::shouldBypass($function)) { + return; + } + if (CallerBoundaryResolver::isCallerVendor()) { + return; + } + if (IgnoreManager::isCallerIgnored()) { + return; + } + + $fullErr = ErrorFactory::createError("$prefix key" . $err->getMessage()); + $handled = ViolationCollector::handle($fullErr, 'yield', null, function: $function); + if ($handled instanceof ErrorMessage) { + throw ErrorFactory::prepareException(new TypePHPTypeError($fullErr->getMessage())); + } } } } if ($itemTypeNode !== null) { - $err = $registry->validate($value, $itemTypeNode, "$prefix value"); - if ($err !== null) { - if ($function !== '' && CallerBoundaryResolver::shouldBypass($function)) { - return; - } - - if (CallerBoundaryResolver::isCallerVendor()) { - return; - } - - if (IgnoreManager::isCallerIgnored()) { - return; - } - - $handled = ViolationCollector::handle($err, 'yield', null, function: $function); - if ($handled instanceof ErrorMessage) { - throw ErrorFactory::prepareException(new TypePHPTypeError($err->getMessage())); + $valOk = match ($valName) { + 'int', 'integer' => \is_int($value), + 'string' => \is_string($value), + 'bool', 'boolean' => \is_bool($value), + default => false, + }; + + if (! $valOk) { + $err = $registry->validate($value, $itemTypeNode, ''); + if ($err !== null) { + if ($function !== '' && CallerBoundaryResolver::shouldBypass($function)) { + return; + } + if (CallerBoundaryResolver::isCallerVendor()) { + return; + } + if (IgnoreManager::isCallerIgnored()) { + return; + } + + $fullErr = ErrorFactory::createError("$prefix value" . $err->getMessage()); + $handled = ViolationCollector::handle($fullErr, 'yield', null, function: $function); + if ($handled instanceof ErrorMessage) { + throw ErrorFactory::prepareException(new TypePHPTypeError($fullErr->getMessage())); + } } } } From a065c805588a2b24c6395ff3369ccd698c966d88 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 19 Nov 2026 19:58:14 +0800 Subject: [PATCH 13/25] Enhance type annotations across various components for improved type safety and clarity --- src/Internal/Ast/ScopeCleaner.php | 2 +- src/Internal/Checker/GeneratorChecker.php | 50 +++++----- src/Internal/Checker/InlineChecker.php | 4 +- src/Internal/Checker/MemberAssignChecker.php | 98 +++++++++---------- src/Internal/Generics/TemplateManager.php | 45 +++++---- src/Internal/Resolver/SpecialTypeResolver.php | 5 + src/Internal/RuntimeTypeChecker.php | 34 +++---- .../Validator/ArrayShapeValidator.php | 12 +-- src/Internal/Validator/GenericValidator.php | 16 +-- 9 files changed, 140 insertions(+), 126 deletions(-) diff --git a/src/Internal/Ast/ScopeCleaner.php b/src/Internal/Ast/ScopeCleaner.php index 081f0cef..52e16838 100644 --- a/src/Internal/Ast/ScopeCleaner.php +++ b/src/Internal/Ast/ScopeCleaner.php @@ -22,7 +22,7 @@ final class ScopeCleaner /** * Cached resolved yield, send, and return contract tuple for the current generator execution scope. * - * @var array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}|null + * @var array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: string|int|null, 6: int, 7: string|int|null}|null */ public ?array $resolvedYieldTypes = null; diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index 0b6faafb..9c93ddca 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -93,7 +93,7 @@ final class GeneratorChecker * Cache for resolved yield & send types of non-generic generators: * [$effectiveFunction] => compiled tuple. * - * @var array + * @var array */ private static array $staticYieldTypeCache = []; @@ -101,7 +101,7 @@ final class GeneratorChecker * 2D Cache for resolved yield & send types of generic generators: * [$effectiveFunction][$templateSignature] => compiled tuple. * - * @var array> + * @var array> */ private static array $genericYieldTypeCache = []; @@ -110,7 +110,7 @@ final class GeneratorChecker * * @var WeakMap, - * types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed} + * types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: string|int|null, 6: int, 7: string|int|null} * }>>|null */ private static ?WeakMap $instanceYieldCache = null; @@ -189,14 +189,14 @@ public static function checkYield( self::OP_BOOL => \is_bool($key), self::OP_FLOAT => \is_float($key) || \is_int($key), self::OP_OBJECT => \is_object($key), - self::OP_CLASS => \is_object($key) && ($key instanceof $keyExtra), - self::OP_MASK => ( - (\is_string($key) && (((int) $keyExtra) & self::BIT_STRING) !== 0) - || (\is_int($key) && (((int) $keyExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) - || (\is_object($key) && (((int) $keyExtra) & self::BIT_OBJECT) !== 0) - || (\is_bool($key) && (((int) $keyExtra) & self::BIT_BOOL) !== 0) - || (\is_float($key) && (((int) $keyExtra) & self::BIT_FLOAT) !== 0) - || (\is_array($key) && (((int) $keyExtra) & self::BIT_ARRAY) !== 0) + self::OP_CLASS => \is_object($key) && \is_string($keyExtra) && ($key instanceof $keyExtra), + self::OP_MASK => \is_int($keyExtra) && ( + (\is_string($key) && ($keyExtra & self::BIT_STRING) !== 0) + || (\is_int($key) && ($keyExtra & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($key) && ($keyExtra & self::BIT_OBJECT) !== 0) + || (\is_bool($key) && ($keyExtra & self::BIT_BOOL) !== 0) + || (\is_float($key) && ($keyExtra & self::BIT_FLOAT) !== 0) + || (\is_array($key) && ($keyExtra & self::BIT_ARRAY) !== 0) ), default => false, }; @@ -222,15 +222,15 @@ public static function checkYield( self::OP_ARRAY_KEY => \is_int($value) || \is_string($value), self::OP_ARRAY => \is_array($value), self::OP_OBJECT => \is_object($value), - self::OP_CLASS => \is_object($value) && ($value instanceof $valExtra), - self::OP_MASK => ( - (\is_string($value) && (((int) $valExtra) & self::BIT_STRING) !== 0) - || (\is_int($value) && (((int) $valExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) - || (\is_object($value) && (((int) $valExtra) & self::BIT_OBJECT) !== 0) - || (\is_bool($value) && (((int) $valExtra) & self::BIT_BOOL) !== 0) - || (\is_float($value) && (((int) $valExtra) & self::BIT_FLOAT) !== 0) - || ($value === null && (((int) $valExtra) & self::BIT_NULL) !== 0) - || (\is_array($value) && (((int) $valExtra) & self::BIT_ARRAY) !== 0) + self::OP_CLASS => \is_object($value) && \is_string($valExtra) && ($value instanceof $valExtra), + self::OP_MASK => \is_int($valExtra) && ( + (\is_string($value) && ($valExtra & self::BIT_STRING) !== 0) + || (\is_int($value) && ($valExtra & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($value) && ($valExtra & self::BIT_OBJECT) !== 0) + || (\is_bool($value) && ($valExtra & self::BIT_BOOL) !== 0) + || (\is_float($value) && ($valExtra & self::BIT_FLOAT) !== 0) + || ($value === null && ($valExtra & self::BIT_NULL) !== 0) + || (\is_array($value) && ($valExtra & self::BIT_ARRAY) !== 0) ), default => false, }; @@ -286,7 +286,7 @@ public static function checkReturn( /** * Resolves and caches the generator's yielded key, value, sent, and return types in memory. * - * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}|null + * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: string|int|null, 6: int, 7: string|int|null}|null */ private static function resolveYieldAndSendTypes( string $function, @@ -397,7 +397,7 @@ private static function resolveYieldAndSendTypes( $rawBindings = TemplateManager::$instanceTemplateBindings !== null ? (TemplateManager::$instanceTemplateBindings[$thisObj] ?? null) : null; - /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}}> $mapEntry */ + /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: string|int|null, 6: int, 7: string|int|null}}> $mapEntry */ $mapEntry = self::$instanceYieldCache[$thisObj] ?? []; $mapEntry[$function] = ['rawBindings' => $rawBindings, 'types' => $types]; self::$instanceYieldCache[$thisObj] = $mapEntry; @@ -436,7 +436,7 @@ private static function resolveYieldAndSendTypes( $rawBindings = TemplateManager::$instanceTemplateBindings !== null ? (TemplateManager::$instanceTemplateBindings[$thisObj] ?? null) : null; - /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed}}> $mapEntry */ + /** @var array, types: array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: string|int|null, 6: int, 7: string|int|null}}> $mapEntry */ $mapEntry = self::$instanceYieldCache[$thisObj] ?? []; $mapEntry[$function] = ['rawBindings' => $rawBindings, 'types' => $types]; self::$instanceYieldCache[$thisObj] = $mapEntry; @@ -452,7 +452,7 @@ private static function resolveYieldAndSendTypes( /** * Extracts and precompiles yielded key, item, sent (TSend), and return (TReturn) contracts. * - * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: mixed, 6: int, 7: mixed} + * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode, 4: int, 5: string|int|null, 6: int, 7: string|int|null} */ private static function compileYieldTypes(TypeNode $returnTypeNode): array { @@ -497,7 +497,7 @@ private static function compileYieldTypes(TypeNode $returnTypeNode): array } /** - * @return array{0: int, 1: mixed} + * @return array{0: int, 1: string|int|null} */ private static function compileCheckOp(?TypeNode $typeNode): array { diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 9172edf4..3ccd9cb4 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -87,9 +87,9 @@ final class InlineChecker private static array $resolvedStaticPropertyTypeCache = []; /** - * In-memory cache for resolved instance property generic types: [$className][$propName] => TypeNode. + * In-memory cache for resolved instance property generic types per object instance. * - * @var \WeakMap> + * @var \WeakMap, props: array}>|null */ private static ?\WeakMap $instancePropertyTypeCache = null; diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 15849aaf..88145d10 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -89,9 +89,9 @@ final class MemberAssignChecker * keyType: ?TypeNode, * valueType: ?TypeNode, * keyOp: int, - * keyExtra: mixed, + * keyExtra: string|int|null, * valOp: int, - * valExtra: mixed + * valExtra: string|int|null * }>>> */ private static array $substitutedElementContractCache = []; @@ -107,9 +107,9 @@ final class MemberAssignChecker * keyType: ?TypeNode, * valueType: ?TypeNode, * keyOp: int, - * keyExtra: mixed, + * keyExtra: string|int|null, * valOp: int, - * valExtra: mixed + * valExtra: string|int|null * }> * }>|null */ @@ -117,9 +117,9 @@ final class MemberAssignChecker /** * Fast packed per-instance contract cache for direct property-dim mutation fast-path in RuntimeTypeChecker: - * [$obj] => array{0: ?array, 1: array} + * [$obj] => array{0: ?array, 1: array} * - * @var WeakMap, 1: array}>|null + * @var WeakMap, 1: array}>|null */ public static ?WeakMap $fastObjectContractCache = null; @@ -288,16 +288,16 @@ public static function checkProperty( self::OP_ARRAY_KEY => \is_int($key) || \is_string($key), self::OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', self::OP_POSITIVE_INT => \is_int($key) && $key > 0, - self::OP_MASK => ( - (\is_string($key) && (((int) $keyExtra) & self::BIT_STRING) !== 0) - || (\is_int($key) && (((int) $keyExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) - || (\is_object($key) && (((int) $keyExtra) & self::BIT_OBJECT) !== 0) - || (\is_bool($key) && (((int) $keyExtra) & self::BIT_BOOL) !== 0) - || (\is_float($key) && (((int) $keyExtra) & self::BIT_FLOAT) !== 0) - || (\is_array($key) && (((int) $keyExtra) & self::BIT_ARRAY) !== 0) + self::OP_MASK => \is_int($keyExtra) && ( + (\is_string($key) && ($keyExtra & self::BIT_STRING) !== 0) + || (\is_int($key) && ($keyExtra & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($key) && ($keyExtra & self::BIT_OBJECT) !== 0) + || (\is_bool($key) && ($keyExtra & self::BIT_BOOL) !== 0) + || (\is_float($key) && ($keyExtra & self::BIT_FLOAT) !== 0) + || (\is_array($key) && ($keyExtra & self::BIT_ARRAY) !== 0) ), self::OP_OBJECT => \is_object($key), - self::OP_CLASS => \is_object($key) && ($key instanceof $keyExtra), + self::OP_CLASS => \is_object($key) && \is_string($keyExtra) && ($key instanceof $keyExtra), default => false, }; } @@ -315,15 +315,15 @@ public static function checkProperty( self::OP_ARRAY_KEY => \is_int($value) || \is_string($value), self::OP_ARRAY => \is_array($value), self::OP_OBJECT => \is_object($value), - self::OP_CLASS => \is_object($value) && ($value instanceof $valExtra), - self::OP_MASK => ( - (\is_string($value) && (((int) $valExtra) & self::BIT_STRING) !== 0) - || (\is_int($value) && (((int) $valExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) - || (\is_object($value) && (((int) $valExtra) & self::BIT_OBJECT) !== 0) - || (\is_bool($value) && (((int) $valExtra) & self::BIT_BOOL) !== 0) - || (\is_float($value) && (((int) $valExtra) & self::BIT_FLOAT) !== 0) - || ($value === null && (((int) $valExtra) & self::BIT_NULL) !== 0) - || (\is_array($value) && (((int) $valExtra) & self::BIT_ARRAY) !== 0) + self::OP_CLASS => \is_object($value) && \is_string($valExtra) && ($value instanceof $valExtra), + self::OP_MASK => \is_int($valExtra) && ( + (\is_string($value) && ($valExtra & self::BIT_STRING) !== 0) + || (\is_int($value) && ($valExtra & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($value) && ($valExtra & self::BIT_OBJECT) !== 0) + || (\is_bool($value) && ($valExtra & self::BIT_BOOL) !== 0) + || (\is_float($value) && ($valExtra & self::BIT_FLOAT) !== 0) + || ($value === null && ($valExtra & self::BIT_NULL) !== 0) + || (\is_array($value) && ($valExtra & self::BIT_ARRAY) !== 0) ), default => false, }; @@ -396,9 +396,9 @@ public static function checkProperty( * keyType: ?TypeNode, * valueType: ?TypeNode, * keyOp: int, - * keyExtra: mixed, + * keyExtra: string|int|null, * valOp: int, - * valExtra: mixed + * valExtra: string|int|null * } $contract */ private static function validatePropertyElementMutationWithContract( @@ -425,16 +425,16 @@ private static function validatePropertyElementMutationWithContract( self::OP_ARRAY_KEY => \is_int($key) || \is_string($key), self::OP_NON_EMPTY_STRING => \is_string($key) && $key !== '', self::OP_POSITIVE_INT => \is_int($key) && $key > 0, - self::OP_MASK => ( - (\is_string($key) && (((int) $keyExtra) & self::BIT_STRING) !== 0) - || (\is_int($key) && (((int) $keyExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) - || (\is_object($key) && (((int) $keyExtra) & self::BIT_OBJECT) !== 0) - || (\is_bool($key) && (((int) $keyExtra) & self::BIT_BOOL) !== 0) - || (\is_float($key) && (((int) $keyExtra) & self::BIT_FLOAT) !== 0) - || (\is_array($key) && (((int) $keyExtra) & self::BIT_ARRAY) !== 0) + self::OP_MASK => \is_int($keyExtra) && ( + (\is_string($key) && ($keyExtra & self::BIT_STRING) !== 0) + || (\is_int($key) && ($keyExtra & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($key) && ($keyExtra & self::BIT_OBJECT) !== 0) + || (\is_bool($key) && ($keyExtra & self::BIT_BOOL) !== 0) + || (\is_float($key) && ($keyExtra & self::BIT_FLOAT) !== 0) + || (\is_array($key) && ($keyExtra & self::BIT_ARRAY) !== 0) ), self::OP_OBJECT => \is_object($key), - self::OP_CLASS => \is_object($key) && ($key instanceof $keyExtra), + self::OP_CLASS => \is_object($key) && \is_string($keyExtra) && ($key instanceof $keyExtra), default => false, }; @@ -460,15 +460,15 @@ private static function validatePropertyElementMutationWithContract( self::OP_ARRAY_KEY => \is_int($value) || \is_string($value), self::OP_ARRAY => \is_array($value), self::OP_OBJECT => \is_object($value), - self::OP_CLASS => \is_object($value) && ($value instanceof $valExtra), - self::OP_MASK => ( - (\is_string($value) && (((int) $valExtra) & self::BIT_STRING) !== 0) - || (\is_int($value) && (((int) $valExtra) & (self::BIT_INT | self::BIT_FLOAT)) !== 0) - || (\is_object($value) && (((int) $valExtra) & self::BIT_OBJECT) !== 0) - || (\is_bool($value) && (((int) $valExtra) & self::BIT_BOOL) !== 0) - || (\is_float($value) && (((int) $valExtra) & self::BIT_FLOAT) !== 0) - || ($value === null && (((int) $valExtra) & self::BIT_NULL) !== 0) - || (\is_array($value) && (((int) $valExtra) & self::BIT_ARRAY) !== 0) + self::OP_CLASS => \is_object($value) && \is_string($valExtra) && ($value instanceof $valExtra), + self::OP_MASK => \is_int($valExtra) && ( + (\is_string($value) && ($valExtra & self::BIT_STRING) !== 0) + || (\is_int($value) && ($valExtra & (self::BIT_INT | self::BIT_FLOAT)) !== 0) + || (\is_object($value) && ($valExtra & self::BIT_OBJECT) !== 0) + || (\is_bool($value) && ($valExtra & self::BIT_BOOL) !== 0) + || (\is_float($value) && ($valExtra & self::BIT_FLOAT) !== 0) + || ($value === null && ($valExtra & self::BIT_NULL) !== 0) + || (\is_array($value) && ($valExtra & self::BIT_ARRAY) !== 0) ), default => false, }; @@ -539,9 +539,9 @@ private static function buildPropertyMutationPlan(string $className, string $pro * keyType: ?TypeNode, * valueType: ?TypeNode, * keyOp: int, - * keyExtra: mixed, + * keyExtra: string|int|null, * valOp: int, - * valExtra: mixed + * valExtra: string|int|null * } */ private static function resolveElementContract(mixed $objectOrClass, string $className, string $propName): ?array @@ -573,9 +573,9 @@ private static function resolveElementContract(mixed $objectOrClass, string $cla * keyType: ?TypeNode, * valueType: ?TypeNode, * keyOp: int, - * keyExtra: mixed, + * keyExtra: string|int|null, * valOp: int, - * valExtra: mixed + * valExtra: string|int|null * } */ private static function resolveElementContractFromPlan( @@ -652,9 +652,9 @@ private static function resolveElementContractFromPlan( * keyType: ?TypeNode, * valueType: ?TypeNode, * keyOp: int, - * keyExtra: mixed, + * keyExtra: string|int|null, * valOp: int, - * valExtra: mixed + * valExtra: string|int|null * } */ private static function buildElementContract(TypeNode $typeNode): ?array @@ -719,7 +719,7 @@ private static function buildElementContract(TypeNode $typeNode): ?array } /** - * @return array{0: int, 1: mixed} + * @return array{0: int, 1: string|int|null} */ private static function compileCheckOp(?TypeNode $typeNode): array { diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 0711e2e1..ba08b1f8 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -489,17 +489,17 @@ final class TemplateManager /** * Compiled binding plan cache per non-relative GenericTypeNode. * - * @var WeakMap, - * classVariances?: array, - * templateList?: list, - * normalizedTypeArgs?: array, - * hasPropagation?: bool, - * allStaticValid?: bool, - * items?: list, + * classVariances: array, + * templateList: list, + * normalizedTypeArgs: array, + * hasPropagation: bool, + * allStaticValid: bool, + * items: list, @@ -1239,7 +1240,6 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t $plan = ['isRelative' => true]; } else { $plan = self::compileGenericBindingPlan($typeNode, $rawClass); - $plan['isRelative'] = false; } self::$compiledNodeBindPlanCache[$typeNode] = $plan; } @@ -1410,6 +1410,7 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t * and non-dependent upper bounds for a (GenericTypeNode, className) pair. * * @return array{ + * isRelative: false, * skip: bool, * className: string, * templates: array, @@ -1435,6 +1436,7 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str { if (! ClassNameValidator::isValid($className) || ! self::isRealTypeSymbol($className)) { return [ + 'isRelative' => false, 'skip' => true, 'className' => $className, 'templates' => [], @@ -1523,6 +1525,7 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str } return [ + 'isRelative' => false, 'skip' => false, 'className' => $className, 'templates' => $templates, @@ -1535,6 +1538,7 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str ]; } catch (\Throwable) { return [ + 'isRelative' => false, 'skip' => false, 'className' => $className, 'templates' => [], @@ -1724,29 +1728,29 @@ private static function propagateBindingsToInstanceProperties( } } - foreach ($plan as $idx => $entry) { + foreach ($plan as $entry) { $prop = $entry['prop']; if (\PHP_VERSION_ID >= 80400 && $prop->isLazy($instance)) { - $propIds[$idx] = -1; + $propIds[] = -1; continue; } if (! $prop->isInitialized($instance)) { - $propIds[$idx] = -1; + $propIds[] = -1; continue; } $propVal = $prop->getValue($instance); if (! \is_object($propVal)) { - $propIds[$idx] = 0; + $propIds[] = 0; continue; } - $propIds[$idx] = spl_object_id($propVal); + $propIds[] = spl_object_id($propVal); if (! DocblockParser::typeReferencesTemplate($entry['type'], $instanceBindings)) { continue; @@ -3353,7 +3357,12 @@ class_exists($name, false) return self::$realTypeSymbolCache[$name] = true; } - return self::$realTypeSymbolCache[$name] = interface_exists($name, false) + return self::$realTypeSymbolCache[$name] = self::nonClassSymbolExistsNoAutoload($name); + } + + private static function nonClassSymbolExistsNoAutoload(string $name): bool + { + return interface_exists($name, false) || enum_exists($name, false) || trait_exists($name, false); } diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index d93aac22..6b44aba1 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -1466,6 +1466,11 @@ class_exists($symbol, false) return true; } + return self::nonClassSymbolExistsNoAutoload($symbol); + } + + private static function nonClassSymbolExistsNoAutoload(string $symbol): bool + { return interface_exists($symbol, false) || enum_exists($symbol, false) || trait_exists($symbol, false); diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 7a418349..215b5393 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -329,16 +329,16 @@ public static function checkPropertyMemberAssign( 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_string($key) && (((int) $kExtra) & MemberAssignChecker::BIT_STRING) !== 0) - || (\is_int($key) && (((int) $kExtra) & (MemberAssignChecker::BIT_INT | MemberAssignChecker::BIT_FLOAT)) !== 0) - || (\is_object($key) && (((int) $kExtra) & MemberAssignChecker::BIT_OBJECT) !== 0) - || (\is_bool($key) && (((int) $kExtra) & MemberAssignChecker::BIT_BOOL) !== 0) - || (\is_float($key) && (((int) $kExtra) & MemberAssignChecker::BIT_FLOAT) !== 0) - || (\is_array($key) && (((int) $kExtra) & MemberAssignChecker::BIT_ARRAY) !== 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) ), MemberAssignChecker::OP_OBJECT => \is_object($key), - MemberAssignChecker::OP_CLASS => \is_object($key) && ($key instanceof $kExtra), + MemberAssignChecker::OP_CLASS => \is_object($key) && \is_string($kExtra) && ($key instanceof $kExtra), default => false, }; } @@ -360,15 +360,15 @@ public static function checkPropertyMemberAssign( 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) && ($value instanceof $vExtra), - MemberAssignChecker::OP_MASK => ( - (\is_string($value) && (((int) $vExtra) & MemberAssignChecker::BIT_STRING) !== 0) - || (\is_int($value) && (((int) $vExtra) & (MemberAssignChecker::BIT_INT | MemberAssignChecker::BIT_FLOAT)) !== 0) - || (\is_object($value) && (((int) $vExtra) & MemberAssignChecker::BIT_OBJECT) !== 0) - || (\is_bool($value) && (((int) $vExtra) & MemberAssignChecker::BIT_BOOL) !== 0) - || (\is_float($value) && (((int) $vExtra) & MemberAssignChecker::BIT_FLOAT) !== 0) - || ($value === null && (((int) $vExtra) & MemberAssignChecker::BIT_NULL) !== 0) - || (\is_array($value) && (((int) $vExtra) & MemberAssignChecker::BIT_ARRAY) !== 0) + 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) ), default => false, }; diff --git a/src/Internal/Validator/ArrayShapeValidator.php b/src/Internal/Validator/ArrayShapeValidator.php index 0633d598..ff2fa757 100644 --- a/src/Internal/Validator/ArrayShapeValidator.php +++ b/src/Internal/Validator/ArrayShapeValidator.php @@ -81,7 +81,7 @@ final class ArrayShapeValidator implements TypeValidatorInterface * @var WeakMap, + * items: list|null, 5: bool}>, * knownKeys: array, * unsealedKeyType: ?TypeNode, * unsealedValueType: ?TypeNode @@ -150,16 +150,16 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali self::CHECK_ARRAY => \is_array($v), self::CHECK_LIST => \is_array($v) && ($v === [] || array_is_list($v)), self::CHECK_EXACT_STRING => \is_string($v) && $v === $item[4], - self::CHECK_STRING_MAP => \is_string($v) && isset($item[4][$v]), + self::CHECK_STRING_MAP => \is_string($v) && \is_array($item[4]) && isset($item[4][$v]), self::CHECK_EXACT_INT => \is_int($v) && $v === $item[4], - self::CHECK_INT_MAP => \is_int($v) && isset($item[4][$v]), + self::CHECK_INT_MAP => \is_int($v) && \is_array($item[4]) && isset($item[4][$v]), self::CHECK_INT_OR_STRING => \is_int($v) || \is_string($v), self::CHECK_TRUE => $v === true, self::CHECK_FALSE => $v === false, self::CHECK_NULL => $v === null, self::CHECK_MIXED => true, self::CHECK_SCALAR => \is_scalar($v), - self::CHECK_CLASS => \is_object($v) && is_a($v, $item[4]), + self::CHECK_CLASS => \is_object($v) && \is_string($item[4]) && is_a($v, $item[4]), self::CHECK_NEGATIVE_INT => \is_int($v) && $v < 0, self::CHECK_NON_NEGATIVE_INT => \is_int($v) && $v >= 0, self::CHECK_NON_POSITIVE_INT => \is_int($v) && $v <= 0, @@ -223,7 +223,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali * @return array{ * isList: bool, * sealed: bool, - * items: list, + * items: list|null, 5: bool}>, * knownKeys: array, * unsealedKeyType: ?TypeNode, * unsealedValueType: ?TypeNode @@ -266,7 +266,7 @@ private static function compileShape(ArrayShapeNode $shapeNode): array } /** - * @return array{0: int, 1: mixed, 2: bool} [checkKind, checkData, nullable] + * @return array{0: int, 1: string|int|array|null, 2: bool} [checkKind, checkData, nullable] */ private static function compileItemType(TypeNode $typeNode): array { diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index c061e52a..44e15c23 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -29,7 +29,6 @@ */ final class GenericValidator implements TypeValidatorInterface { - private const KIND_FALLBACK = 0; private const KIND_LIST = 1; private const KIND_NON_EMPTY_LIST = 2; private const KIND_ARRAY = 3; @@ -62,7 +61,7 @@ final class GenericValidator implements TypeValidatorInterface ]; /** - * @var WeakMap|null + * @var WeakMap|null */ private static ?WeakMap $compiledGenericCache = null; @@ -122,7 +121,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali $count = \count($value); $valueTypeNode = $compiled[1]; - if ($valueTypeNode === null || $count === 0) { + if (! ($valueTypeNode instanceof TypeNode) || $count === 0) { return null; } @@ -148,7 +147,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali } $valueTypeNode = $compiled[1]; - if ($valueTypeNode === null) { + if (! ($valueTypeNode instanceof TypeNode)) { return null; } @@ -176,7 +175,9 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali return ErrorFactory::createError($context . ' must be of type int, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } - [$minVal, $maxVal] = $compiled[1]; + /** @var array{0: ?int, 1: ?int} $bounds */ + $bounds = $compiled[1]; + [$minVal, $maxVal] = $bounds; $redact = $isSensitive || Config::isRedactValuesEnabled(); if ($minVal !== null && $value < $minVal) { @@ -215,9 +216,8 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali } if ($kind === self::KIND_OBJECT_GENERIC) { - /** @var class-string|null $targetClass */ $targetClass = $compiled[1]; - if ($targetClass === null) { + if (! \is_string($targetClass)) { return null; } @@ -236,7 +236,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali } /** - * @return array{0: int, 1: mixed} + * @return array{0: int, 1: TypeNode|array{0: ?int, 1: ?int}|string|null} */ private function compileGeneric(GenericTypeNode $node): array { From e05456c215c76314991489c85fb602596d5f8dbc Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 19 Nov 2026 20:34:42 +0800 Subject: [PATCH 14/25] Enhance TemplateManager with additional caching mechanisms for generic type bindings and improve property binding propagation --- src/Internal/Generics/TemplateManager.php | 101 ++++++++++++++++++---- 1 file changed, 82 insertions(+), 19 deletions(-) diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index ba08b1f8..4851ca77 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -564,6 +564,43 @@ final class TemplateManager */ private static array $refClassCache = []; + /** + * Secondary string-keyed binding plan cache for freshly substituted GenericTypeNode instances: + * [$className][$nodeString] => compiled plan. + * + * @var array, + * classVariances: array, + * templateList: list, + * normalizedTypeArgs: array, + * hasPropagation: bool, + * allStaticValid: bool, + * items: list + * }> + * }>> + */ + private static array $compiledBindPlanBySigCache = []; + + /** + * Memoized substituted GenericTypeNode for property binding propagation: + * [$className][$propIndex][$bindingsSig] => ?GenericTypeNode. + * + * @var array>> + */ + private static array $propagatedPropTypeCache = []; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ @@ -1434,8 +1471,13 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t */ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, string $className): array { + $sigKey = (string) $typeNode; + if (isset(self::$compiledBindPlanBySigCache[$className][$sigKey])) { + return self::$compiledBindPlanBySigCache[$className][$sigKey]; + } + if (! ClassNameValidator::isValid($className) || ! self::isRealTypeSymbol($className)) { - return [ + return self::$compiledBindPlanBySigCache[$className][$sigKey] = [ 'isRelative' => false, 'skip' => true, 'className' => $className, @@ -1524,7 +1566,7 @@ private static function compileGenericBindingPlan(GenericTypeNode $typeNode, str ]; } - return [ + return self::$compiledBindPlanBySigCache[$className][$sigKey] = [ 'isRelative' => false, 'skip' => false, 'className' => $className, @@ -1615,21 +1657,24 @@ private static function propagationPlan(string $className): array } $plan = []; + $classTemplates = DocblockParser::parseClassTemplates($className); - try { - /** @var class-string $className */ - $ref = new \ReflectionClass($className); - foreach ($ref->getProperties() as $prop) { - if ($prop->isStatic()) { - continue; - } + if ($classTemplates !== []) { + try { + /** @var class-string $className */ + $ref = new \ReflectionClass($className); + foreach ($ref->getProperties() as $prop) { + if ($prop->isStatic()) { + continue; + } - $propType = DocblockParser::parseProperty($className, $prop->getName()); - if ($propType instanceof GenericTypeNode) { - $plan[] = ['prop' => $prop, 'type' => $propType]; + $propType = DocblockParser::parseProperty($className, $prop->getName()); + if ($propType instanceof GenericTypeNode && DocblockParser::typeReferencesTemplate($propType, $classTemplates)) { + $plan[] = ['prop' => $prop, 'type' => $propType]; + } } + } catch (\Throwable) { } - } catch (\Throwable) { } return self::$propagationPlanCache[$className] = $plan; @@ -1720,15 +1765,18 @@ private static function propagateBindingsToInstanceProperties( $propIds = []; try { + $className = $instance::class; + if (\PHP_VERSION_ID >= 80400) { - $className = $instance::class; $refClass = self::$refClassCache[$className] ??= new \ReflectionClass($className); if ($refClass->isUninitializedLazyObject($instance)) { return; } } - foreach ($plan as $entry) { + $bindingsSig = null; + + foreach ($plan as $idx => $entry) { $prop = $entry['prop']; if (\PHP_VERSION_ID >= 80400 && $prop->isLazy($instance)) { @@ -1752,12 +1800,27 @@ private static function propagateBindingsToInstanceProperties( $propIds[] = spl_object_id($propVal); - if (! DocblockParser::typeReferencesTemplate($entry['type'], $instanceBindings)) { - continue; + if ($bindingsSig === null) { + $bindingsSig = ''; + foreach ($instanceBindings as $k => $v) { + $bindingsSig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; + } + } + + if (isset(self::$propagatedPropTypeCache[$className][$idx]) && \array_key_exists($bindingsSig, self::$propagatedPropTypeCache[$className][$idx])) { + $resolvedPropType = self::$propagatedPropTypeCache[$className][$idx][$bindingsSig]; + } else { + $resolvedPropType = null; + if (DocblockParser::typeReferencesTemplate($entry['type'], $instanceBindings)) { + $sub = TemplateSubstitutor::substitute($entry['type'], $instanceBindings); + if ($sub instanceof GenericTypeNode) { + $resolvedPropType = $sub; + } + } + self::$propagatedPropTypeCache[$className][$idx][$bindingsSig] = $resolvedPropType; } - $resolvedPropType = TemplateSubstitutor::substitute($entry['type'], $instanceBindings); - if ($resolvedPropType instanceof GenericTypeNode) { + if ($resolvedPropType !== null) { self::bindInstanceFromNode($propVal, $resolvedPropType, forceBind: true, refineOnly: true); } } From 62f06c52564e4305a38fc32296c3ddf5cd223949 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 19 Nov 2026 21:30:55 +0800 Subject: [PATCH 15/25] Enhance ContractVisitor and EliminationSafetyPolicy to support traits, improve FunctionContractInjector with elimination checks, and add property dimension assignment checks in RuntimeTypeChecker --- src/Internal/Ast/ContractVisitor.php | 16 +- .../Elimination/EliminationSafetyPolicy.php | 10 +- src/Internal/Ast/FunctionContractInjector.php | 218 ++++++++++++++++-- src/Internal/Ast/NodeBuilder.php | 18 ++ src/Internal/Io/CacheManager.php | 2 +- src/Internal/RuntimeTypeChecker.php | 95 ++++++++ 6 files changed, 338 insertions(+), 21 deletions(-) diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index b49c3b53..77dcdb32 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -64,7 +64,7 @@ final class ContractVisitor extends NodeVisitorAbstract private string $currentNamespace = ''; /** - * @var list + * @var list */ private array $classStack = []; @@ -904,6 +904,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ $hasPropertyWithDoc = false; $isReadonly = false; $isFinal = false; + $isTrait = $node instanceof Node\Stmt\Trait_; $doc = $node->getDocComment(); if ($doc === null && $typeName !== null && StubManager::hasClassStub($typeName)) { @@ -975,6 +976,9 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } elseif ($node instanceof Node\Stmt\Enum_) { $hasRealInheritance = $node->implements !== []; $hasInheritance = $hasRealInheritance; + } elseif ($node instanceof Node\Stmt\Trait_) { + $hasRealInheritance = true; + $hasInheritance = true; } if ($typeName !== null && ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_)) { @@ -1036,6 +1040,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ 'isReadonly' => $isReadonly, 'isFinal' => $isFinal, 'hasTemplates' => $hasTemplates, + 'isTrait' => $isTrait, ]; } @@ -1899,6 +1904,15 @@ private function wrapPropertyMemberAssignCheck( array $chain, int $line ): Node\Expr\Ternary { + if (\count($chain) === 1 && $chain[0][0] === 'dim') { + $dimExpr = $chain[0][1] instanceof Node\Expr + ? $chain[0][1] + : new Node\Expr\ConstFetch(new Node\Name('null')); + $checkCall = NodeBuilder::createPropertyDimAssignCheckCall($targetExpr, $propName, $dimExpr, $valueExpr); + + return NodeBuilder::createTernaryThrowExpr($checkCall, $line); + } + $chainAst = $this->buildChainAst($chain); $checkCall = NodeBuilder::createPropertyMemberAssignCheckCall($targetExpr, $propName, $chainAst, $valueExpr); diff --git a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php index b23413e5..dd6bc3ba 100644 --- a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php +++ b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php @@ -61,7 +61,7 @@ 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 (cannot override or be overridden). + * - 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. * @@ -91,6 +91,10 @@ public static function isReturnEliminationSafe( return true; } + if ($classContext['isTrait'] ?? false) { + return false; + } + $hasRealInheritance = $classContext['hasRealInheritance'] ?? true; if (! $hasRealInheritance) { return true; @@ -139,6 +143,10 @@ public static function isGeneratorEliminationSafe( return true; } + if ($classContext['isTrait'] ?? false) { + return false; + } + $hasRealInheritance = $classContext['hasRealInheritance'] ?? true; if (! $hasRealInheritance) { return true; diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 59dd940b..20b3e7e6 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -8,15 +8,19 @@ use PhpParser\Node; use PhpParser\NodeTraverser; use PhpParser\NodeVisitorAbstract; +use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; 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\DocblockParser; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StubManager; /** @@ -138,11 +142,7 @@ public static function inject( $useDynamicMethodKey = $isClassMethod && ! $isPrivate && ! $isFinalClass; - $injectedStmts = []; - if ($hasParam) { - $injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg, $isReadonlyClass, $needsReturnVars, $useDynamicMethodKey); - } - + $phpDocNode = null; $returnTypeNode = null; $hasMethodTemplates = false; $declaredTemplates = []; @@ -159,6 +159,42 @@ public static function inject( } } + $isTrait = $classContext['isTrait'] ?? false; + + if ( + $hasParam + && ! $isConstructor + && ! $isMagicGet + && ! $isMagicCall + && ! $hasMethodTemplates + && ! $hasParamOut + && ! $hasSelfOut + && ! $isTrait + && ! ($isClassMethod && $node->isStatic() && $hasClassTemplates) + && self::canEliminateSetupScope( + $node, + $phpDocNode, + $docText, + $isClassMethod, + $isPrivate, + $hasRealInheritance, + $returnTypeNode, + $hasReturn + ) + ) { + $hasParam = false; + $needsReturnVars = false; + } + + if (! $hasParam && ! $hasReturn && ! $hasParamOut && ! $hasSelfOut) { + return; + } + + $injectedStmts = []; + if ($hasParam) { + $injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg, $isReadonlyClass, $needsReturnVars, $useDynamicMethodKey); + } + $trustedParamTypes = self::collectTrustedParamTypes($node, $doc, $declaredTemplates, $currentFile); if ($hasReturn || $hasParamOut || $hasSelfOut) { @@ -197,6 +233,142 @@ public static function inject( $node->stmts = [...$injectedStmts, ...$node->stmts]; } + private static function canEliminateSetupScope( + Node\Stmt\Function_|Node\Stmt\ClassMethod $node, + ?PhpDocNode $phpDocNode, + string $docText, + bool $isClassMethod, + bool $isPrivate, + bool $hasRealInheritance, + ?TypeNode $returnTypeNode, + bool $hasReturn + ): bool { + if (! Config::isEliminateStaticallyProvenChecksEnabled()) { + return false; + } + + if ($node->attrGroups !== [] || str_contains($docText, ' is ')) { + return false; + } + + if ($isClassMethod && ! $isPrivate && $hasRealInheritance) { + return false; + } + + if ($hasReturn && ($returnTypeNode !== null && ConditionalChecker::containsConditional($returnTypeNode))) { + return false; + } + + $paramTags = $phpDocNode !== null ? DocblockExtractor::getParamTags($phpDocNode) : []; + + foreach ($node->params as $param) { + if ($param->variadic || ! ($param->var instanceof Node\Expr\Variable) || ! \is_string($param->var->name)) { + return false; + } + + $paramDoc = $param->getDocComment() !== null ? $param->getDocComment()->getText() : ''; + $effectiveDoc = $docText . ' ' . $paramDoc; + if (self::isCallableCandidate($param, $effectiveDoc) || self::isIterableCandidate($param, $effectiveDoc)) { + return false; + } + + $pName = $param->var->name; + $paramTag = $paramTags[$pName] ?? null; + + if ($paramTag === null) { + if ($hasRealInheritance) { + return false; + } + + continue; + } + + if (! self::nativeParamSatisfiesDocType($param->type, $paramTag->type)) { + return false; + } + } + + return true; + } + + private static function nativeParamSatisfiesDocType( + Node\Identifier|Node\Name|Node\ComplexType|null $nativeType, + TypeNode $docType + ): bool { + if ($docType instanceof IdentifierTypeNode && strtolower($docType->name) === 'mixed') { + return true; + } + + if ($nativeType === null) { + return false; + } + + if ($nativeType instanceof Node\NullableType) { + if ($docType instanceof NullableTypeNode) { + return self::nativeParamSatisfiesDocType($nativeType->type, $docType->type); + } + + if ($docType instanceof UnionTypeNode) { + $hasNull = false; + foreach ($docType->types as $member) { + if ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'null') { + $hasNull = true; + + break; + } + } + + return $hasNull && self::nativeParamSatisfiesDocType($nativeType->type, $docType); + } + + return false; + } + + if ($nativeType instanceof Node\UnionType) { + foreach ($nativeType->types as $t) { + if (! self::nativeParamSatisfiesDocType($t, $docType)) { + return false; + } + } + + return true; + } + + if ($docType instanceof NullableTypeNode) { + return self::nativeParamSatisfiesDocType($nativeType, $docType->type); + } + + if ($docType instanceof UnionTypeNode) { + foreach ($docType->types as $member) { + if (self::nativeParamSatisfiesDocType($nativeType, $member)) { + return true; + } + } + + return false; + } + + if ($nativeType instanceof Node\Identifier && $docType instanceof IdentifierTypeNode) { + $native = strtolower($nativeType->name); + $doc = strtolower($docType->name); + + if ($native === $doc) { + return true; + } + + return match ($native) { + 'int' => \in_array($doc, ['integer', 'float', 'double', 'array-key', 'scalar', 'numeric', 'number'], true), + 'string' => \in_array($doc, ['array-key', 'scalar'], true), + 'bool' => \in_array($doc, ['boolean', 'scalar'], true), + 'float' => \in_array($doc, ['double', 'scalar', 'numeric', 'number'], true), + 'array' => $doc === 'iterable', + default => false, + }; + } + + return false; + } + /** * Extracts concrete parameter contracts and verifies they are never mutated in the body. * @@ -1139,6 +1311,10 @@ private static function wrapGeneratorReturns( ? GeneratorEvaluator::extractContract($returnTypeNode) : null; + $explicitGenContract = ($returnTypeNode !== null && Config::isEliminateStaticallyProvenChecksEnabled()) + ? GeneratorEvaluator::extractContract($returnTypeNode) + : null; + if ($genContract !== null) { self::tagPrecedingAssignments($stmts); } @@ -1147,6 +1323,7 @@ private static function wrapGeneratorReturns( $traverser->addVisitor(new class ( $thisArg, $genContract, + $explicitGenContract, $currentFile, $needsReturnVars, $byRefParams, @@ -1155,12 +1332,14 @@ private static function wrapGeneratorReturns( ) 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 */ public function __construct( private Node\Expr $thisArg, private ?array $genContract, + private ?array $explicitGenContract, private string $currentFile, private bool $needsReturnVars, private array $byRefParams, @@ -1214,8 +1393,9 @@ public function enterNode(Node $n): int|Node|array|null $precedingValueExpr ); - $wrapSend = $this->genContract === null - || ! GeneratorEvaluator::canEliminateSend($this->genContract['send']); + $sendContract = $this->genContract ?? $this->explicitGenContract; + $wrapSend = $sendContract === null + || ! GeneratorEvaluator::canEliminateSend($sendContract['send']); if (! $wrapYield && ! $wrapSend && $this->byRefParams === []) { return null; @@ -1294,13 +1474,14 @@ public function enterNode(Node $n): int|Node|array|null $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; if ( - $this->genContract !== null - && GeneratorEvaluator::canEliminateGeneratorReturn( - $candidateExpr, - $this->genContract['return'], - $this->currentFile, - $this->trustedParamTypes - ) + ($this->genContract !== null + && GeneratorEvaluator::canEliminateGeneratorReturn( + $candidateExpr, + $this->genContract['return'], + $this->currentFile, + $this->trustedParamTypes + )) + || ($this->explicitGenContract !== null && $this->explicitGenContract['return'] === null) ) { return $exitStmts !== [] ? [...$exitStmts, $n] : $n; } @@ -1351,10 +1532,11 @@ public function enterNode(Node $n): int|Node|array|null $newStmts = [...$newStmts, ...$exitStmts]; } - if ( - $genContract === null - || ! GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile, $trustedParamTypes) - ) { + $canSkipImplicitGenReturn = ($genContract !== null + && GeneratorEvaluator::canEliminateGeneratorReturn(null, $genContract['return'], $currentFile, $trustedParamTypes)) + || ($explicitGenContract !== null && $explicitGenContract['return'] === null); + + if (! $canSkipImplicitGenReturn) { $scopeArg = new Node\Expr\BinaryOp\Coalesce( new Node\Expr\Variable('__typephpScope'), new Node\Expr\ConstFetch(new Node\Name('null')) diff --git a/src/Internal/Ast/NodeBuilder.php b/src/Internal/Ast/NodeBuilder.php index 10a4ba00..d954c40d 100644 --- a/src/Internal/Ast/NodeBuilder.php +++ b/src/Internal/Ast/NodeBuilder.php @@ -141,6 +141,24 @@ public static function createPropertyMemberAssignCheckCall( ); } + public static function createPropertyDimAssignCheckCall( + Node\Expr $objectOrClassExpr, + string $propertyName, + Node\Expr $dimExpr, + Node\Expr $valueExpr + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name('\TypePHP\Internal\RuntimeTypeChecker::checkPropertyDimAssign'), + [ + new Node\Arg($objectOrClassExpr), + new Node\Arg(new Node\Scalar\String_($propertyName)), + new Node\Arg($dimExpr), + new Node\Arg($valueExpr), + new Node\Arg(new Node\Scalar\MagicConst\File()), + ] + ); + } + public static function createConstantCheckCall( string $constantName, Node\Expr $valueExpr, diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index fb3d0fe4..da2b5f96 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -16,7 +16,7 @@ final class CacheManager /** * Cache version prefix string. Bump this whenever AST printer/transformation rules change. */ - public const VERSION_PREFIX = 'v0.13.0_'; + public const VERSION_PREFIX = 'v0.14.1_'; /** * Config keys that only steer runtime behaviour and never change the transformed source. diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 215b5393..30c7483c 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -446,6 +446,101 @@ public static function checkMemberAssign( return $res; } + /** + * Fast-path for 1-level property dimension assignments ($obj->prop[$key] = $val or $obj->prop[] = $val), + * avoiding per-write [['dim', $key]] array allocations. + */ + public static function checkPropertyDimAssign( + mixed $objectOrClass, + string $propName, + mixed $key, + mixed $value, + string $file + ): mixed { + if (! self::$isEnabled || ! self::$inlinePropertiesEnabled) { + return $value; + } + + if ( + self::$arrayValidationHybrid + && \is_object($objectOrClass) + && MemberAssignChecker::$fastObjectContractCache !== null + ) { + $entry = MemberAssignChecker::$fastObjectContractCache[$objectOrClass] ?? null; + if ($entry !== null && isset($entry[1][$propName])) { + $rawBindings = TemplateManager::$instanceTemplateBindings !== null + ? (TemplateManager::$instanceTemplateBindings[$objectOrClass] ?? null) + : null; + + if ($entry[0] === $rawBindings) { + $c = $entry[1][$propName]; + + if (! $c[0] || $key === null) { + $keyOk = true; + if (! $c[0] && $key !== null && $c[1] !== MemberAssignChecker::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) + ), + MemberAssignChecker::OP_OBJECT => \is_object($key), + MemberAssignChecker::OP_CLASS => \is_object($key) && \is_string($kExtra) && ($key instanceof $kExtra), + default => false, + }; + } + + if ($keyOk) { + $vOp = $c[3]; + if ($vOp === MemberAssignChecker::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) + ), + default => false, + }; + + if ($valOk) { + return $value; + } + } + } + } + } + } + + return self::checkPropertyMemberAssign($objectOrClass, $propName, [['dim', $key]], $value, $file); + } + /** * Pre-binds generic template state on a class before its constructor executes. * From 6e867c9be744a5b121eab3b592e297e79ee99647 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 20 Nov 2026 18:25:07 +0800 Subject: [PATCH 16/25] Enhance ParamChecker and TemplateManager with improved type handling and caching mechanisms, and add ClosureParameterTemplateOverwritingTest to ensure template preservation in closures --- src/Internal/Checker/ParamChecker.php | 63 +++++ src/Internal/Generics/TemplateManager.php | 233 +++++++++++++++++- ...losureParameterTemplateOverwritingTest.php | 139 +++++++++++ 3 files changed, 431 insertions(+), 4 deletions(-) create mode 100644 tests/TypeChecking/Generics/ClosureParameterTemplateOverwritingTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 043f3b4e..76545d83 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -761,6 +761,13 @@ private static function inferTemplatesFromClosures( $inferredCandidate = self::extractTypeFromClosureParameter($closureParams[$idx]); if ($inferredCandidate !== null) { + if ($targetObj !== null) { + $existingType = TemplateManager::getInstanceBoundTypeFast($targetObj, $tName); + if ($existingType !== null && TemplateManager::checkVariance($existingType, $inferredCandidate, GenericTypeNode::VARIANCE_COVARIANT)) { + continue; + } + } + $templateTag = $templates[$tName]; $satisfiesBound = true; @@ -1319,6 +1326,7 @@ private static function inferArrayTemplatesFromAllElements( $inferredKeyType = null; $inferredValType = null; + $hasEmptyValArray = false; foreach ($sampleItems as $key => $item) { if ($keyTName !== null) { @@ -1326,11 +1334,25 @@ private static function inferArrayTemplatesFromAllElements( $inferredKeyType = ($inferredKeyType === null) ? $keyType : self::unifyTypes($inferredKeyType, $keyType); } if ($valTName !== null) { + if ($item === []) { + $hasEmptyValArray = true; + + continue; + } $valType = TemplateManager::inferTypeFromValue($item); $inferredValType = ($inferredValType === null) ? $valType : self::unifyTypes($inferredValType, $valType); } } + if ($valTName !== null && $hasEmptyValArray) { + $emptyListNode = TemplateManager::inferTypeFromValue([]); + if ($inferredValType === null) { + $inferredValType = $emptyListNode; + } elseif (! self::isCollectionTypeNode($inferredValType)) { + $inferredValType = self::unifyTypes($inferredValType, $emptyListNode); + } + } + if ($keyTName !== null && $inferredKeyType !== null) { self::bindTemplateIfUnbound($keyTName, $inferredKeyType, $effectiveFunction, $thisObj, $templates, $classTemplates); } @@ -1502,16 +1524,57 @@ private static function inferSingleTemplateFromArraySamples( array $classTemplates = [] ): void { $inferredType = null; + $hasEmptyArray = false; + foreach ($sampleItems as $item) { + if ($item === []) { + $hasEmptyArray = true; + + continue; + } $itemType = TemplateManager::inferTypeFromValue($item); $inferredType = ($inferredType === null) ? $itemType : self::unifyTypes($inferredType, $itemType); } + if ($hasEmptyArray) { + $emptyListNode = TemplateManager::inferTypeFromValue([]); + if ($inferredType === null) { + $inferredType = $emptyListNode; + } elseif (! self::isCollectionTypeNode($inferredType)) { + $inferredType = self::unifyTypes($inferredType, $emptyListNode); + } + } + if ($inferredType !== null) { self::bindTemplateIfUnbound($templateName, $inferredType, $effectiveFunction, $thisObj, $templates, $classTemplates); } } + private static function isCollectionTypeNode(TypeNode $node): bool + { + if ($node instanceof IdentifierTypeNode) { + return isset(self::COLLECTION_TYPES[strtolower($node->name)]); + } + + if ($node instanceof GenericTypeNode) { + return isset(self::COLLECTION_TYPES[strtolower((string) $node->type)]); + } + + if ($node instanceof ArrayTypeNode) { + return true; + } + + if ($node instanceof UnionTypeNode) { + foreach ($node->types as $member) { + if (self::isCollectionTypeNode($member)) { + return true; + } + } + } + + return false; + } + /** * Extracts items for template inference, using hybrid sampling for arrays > 128 items. * diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 4851ca77..fb330cd5 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -601,6 +601,21 @@ final class TemplateManager */ private static array $propagatedPropTypeCache = []; + /** + * Cache of properties whose @var type references a given template name: + * [$className][$templateName] => list + * + * @var array>> + */ + private static array $templatePropertyPlanCache = []; + + /** + * WeakMap caching verified (templateName, expectedTypeString) pairs for shallow 'list'/'array' instances. + * + * @var WeakMap>>|null + */ + private static ?WeakMap $verifiedShallowRefinements = null; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ @@ -636,6 +651,8 @@ public static function reset(): void self::$compiledRelativeNodeBindPlanCache = null; self::$compiledUnionMembersCache = null; self::$noInheritedBindingsClasses = []; + self::$templatePropertyPlanCache = []; + self::$verifiedShallowRefinements = null; } /** @@ -2189,6 +2206,15 @@ private static function bindSingleTemplateArgument( } } + if ( + $existingTypeNode instanceof IdentifierTypeNode + && ($existingTypeNode->name === 'list' || $existingTypeNode->name === 'array') + && self::isSpecializedCollectionType($expectedTypeNode) + && self::verifyShallowCollectionRefinement($instance, $templateName, $existingTypeNode->name, $expectedTypeNode, $existingBindings) + ) { + return null; + } + $contextPrefix = $context !== '' ? (str_ends_with($context, ':') ? $context . ' ' : $context . ' ') : ' '; return ErrorFactory::createError( @@ -2672,6 +2698,10 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return true; } + if (self::isArrayKeyEquivalent($existing) && self::isArrayKeyEquivalent($expected)) { + return true; + } + if ($existing instanceof IdentifierTypeNode && $expected instanceof IdentifierTypeNode) { $existingName = $existing->name; $expectedName = $expected->name; @@ -3150,7 +3180,27 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge if (! isset(self::COLLECTION_SUBTYPES[$lowerExpected][$lowerExisting])) { return false; } - } elseif (! is_a((string) $existing->type, $expectedClassName, true)) { + + $existingArgs = self::normalizeCollectionTypeArgs($existing->genericTypes); + $expectedArgs = self::normalizeCollectionTypeArgs($expected->genericTypes); + + if (\count($existingArgs) === 2 && \count($expectedArgs) === 1) { + $expectedArgs = self::expandCollectionTypeArgs($lowerExpected, $expectedArgs); + } elseif (\count($existingArgs) === 1 && \count($expectedArgs) === 2) { + $existingArgs = self::expandCollectionTypeArgs($lowerExisting, $existingArgs); + } + + foreach ($expectedArgs as $idx => $expectedInner) { + $existingInner = $existingArgs[$idx] ?? (self::$mixedNode ??= new IdentifierTypeNode('mixed')); + if (! self::checkVariance($existingInner, $expectedInner, GenericTypeNode::VARIANCE_COVARIANT)) { + return false; + } + } + + return true; + } + + if (! is_a((string) $existing->type, $expectedClassName, true)) { return false; } @@ -3169,11 +3219,9 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge $useSiteVariance = $expected->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; $declaredVariance = $declaredVariances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; - $defaultVariance = $isCollection ? GenericTypeNode::VARIANCE_COVARIANT : GenericTypeNode::VARIANCE_INVARIANT; - $innerVariance = ($useSiteVariance !== GenericTypeNode::VARIANCE_INVARIANT) ? $useSiteVariance - : ($declaredVariance !== GenericTypeNode::VARIANCE_INVARIANT ? $declaredVariance : $defaultVariance); + : ($declaredVariance !== GenericTypeNode::VARIANCE_INVARIANT ? $declaredVariance : GenericTypeNode::VARIANCE_INVARIANT); if (! self::checkVariance($existingInner, $expectedInner, $innerVariance)) { return false; @@ -3183,6 +3231,183 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge return true; } + /** + * @param array $args + * + * @return list + */ + private static function normalizeCollectionTypeArgs(array $args): array + { + $args = array_values($args); + if ($args === []) { + return [self::$mixedNode ??= new IdentifierTypeNode('mixed')]; + } + + if (\count($args) >= 2) { + return [$args[0], $args[1]]; + } + + return [$args[0]]; + } + + /** + * Expands a 1-arg collection generic [V] into [K, V] using its implicit key type. + * + * @param list $args + * + * @return array{0: TypeNode, 1: TypeNode} + */ + private static function expandCollectionTypeArgs(string $lowerBase, array $args): array + { + $keyNode = ($lowerBase === 'list' || $lowerBase === 'non-empty-list') + ? (self::$intNode ??= new IdentifierTypeNode('int')) + : new IdentifierTypeNode('array-key'); + + return [$keyNode, $args[0]]; + } + + private static function isArrayKeyEquivalent(TypeNode $node): bool + { + if ($node instanceof IdentifierTypeNode) { + return strtolower($node->name) === 'array-key'; + } + + if ($node instanceof UnionTypeNode && \count($node->types) === 2) { + $hasInt = false; + $hasString = false; + + foreach ($node->types as $member) { + if (! ($member instanceof IdentifierTypeNode)) { + return false; + } + + $lower = strtolower($member->name); + if ($lower === 'int' || $lower === 'integer') { + $hasInt = true; + } elseif ($lower === 'string') { + $hasString = true; + } else { + return false; + } + } + + return $hasInt && $hasString; + } + + return false; + } + + private static function isSpecializedCollectionType(TypeNode $node): bool + { + if ($node instanceof ArrayTypeNode) { + return true; + } + + if ($node instanceof GenericTypeNode) { + return isset(self::COLLECTION_SUBTYPES[strtolower((string) $node->type)]); + } + + return false; + } + + /** + * Lazily verifies an instance's runtime array properties when a shallow 'list'/'array' + * binding is checked against a specialized collection type (e.g. list, array). + * + * @param array $existingBindings + */ + private static function verifyShallowCollectionRefinement( + object $instance, + string $templateName, + string $existingShallowName, + TypeNode $expectedTypeNode, + array $existingBindings + ): bool { + if ($existingShallowName === 'array') { + $expectedBase = $expectedTypeNode instanceof GenericTypeNode + ? strtolower((string) $expectedTypeNode->type) + : ''; + + if ($expectedBase === 'list' || $expectedBase === 'non-empty-list') { + return false; + } + } + + $expectedKey = (string) $expectedTypeNode; + self::$verifiedShallowRefinements ??= new WeakMap(); + $cached = self::$verifiedShallowRefinements[$instance][$templateName][$expectedKey] ?? null; + if ($cached !== null) { + return $cached; + } + + $actualClass = $instance::class; + if (! isset(self::$templatePropertyPlanCache[$actualClass][$templateName])) { + $plan = []; + + try { + $ref = new \ReflectionClass($actualClass); + $needle = [$templateName => true]; + + foreach ($ref->getProperties() as $prop) { + if ($prop->isStatic()) { + continue; + } + + $propType = DocblockParser::parseProperty($actualClass, $prop->getName()); + if ($propType !== null && DocblockParser::typeReferencesTemplate($propType, $needle)) { + $plan[] = ['prop' => $prop, 'type' => $propType]; + } + } + } catch (\Throwable) { + } + + self::$templatePropertyPlanCache[$actualClass][$templateName] = $plan; + } + + $propPlan = self::$templatePropertyPlanCache[$actualClass][$templateName]; + if ($propPlan === []) { + return false; + } + + [$classTemplates] = self::hierarchyTemplatesForClass($actualClass); + $testBindings = $existingBindings; + $testBindings[$templateName] = $expectedTypeNode; + $registry = \TypePHP\Internal\RuntimeTypeChecker::getRegistry(); + $checkedAny = false; + + foreach ($propPlan as $entry) { + $prop = $entry['prop']; + if ((\PHP_VERSION_ID >= 80400 && $prop->isLazy($instance)) || ! $prop->isInitialized($instance)) { + continue; + } + + $checkedAny = true; + $val = $prop->getValue($instance); + $substitutedType = TemplateSubstitutor::substitute($entry['type'], $testBindings, $classTemplates); + $err = $registry->validate($val, $substitutedType, ''); + + if ($err !== null) { + /** @var array> $instMap */ + $instMap = self::$verifiedShallowRefinements[$instance] ?? []; + $instMap[$templateName][$expectedKey] = false; + self::$verifiedShallowRefinements[$instance] = $instMap; + + return false; + } + } + + if (! $checkedAny) { + return false; + } + + /** @var array> $instMap */ + $instMap = self::$verifiedShallowRefinements[$instance] ?? []; + $instMap[$templateName][$expectedKey] = true; + self::$verifiedShallowRefinements[$instance] = $instMap; + + return true; + } + private static function isSubclass(string $sub, string $super): bool { if (isset(self::$subclassCache[$sub][$super])) { diff --git a/tests/TypeChecking/Generics/ClosureParameterTemplateOverwritingTest.php b/tests/TypeChecking/Generics/ClosureParameterTemplateOverwritingTest.php new file mode 100644 index 00000000..101cdc51 --- /dev/null +++ b/tests/TypeChecking/Generics/ClosureParameterTemplateOverwritingTest.php @@ -0,0 +1,139 @@ + + */ + public array $items; + + /** + * @param array $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } + + /** + * Calling filter with a Closure that typehints a supertype (e.g. fn(ReproStatement $s)) + * must NOT overwrite this instance's reified TValue in WeakMap. + * + * @param null|Closure(TValue): bool $predicate + * + * @return self + */ + public function filter(?Closure $predicate = null): self + { + if ($predicate === null) { + return new self(array_values(array_filter($this->items))); + } + + $res = []; + foreach ($this->items as $item) { + if ($predicate($item)) { + $res[] = $item; + } + } + + return new self($res); + } + + /** + * Method-level template @template R must still be inferred from closure return types. + * + * @template R + * + * @param Closure(TValue): R $mapper + * + * @return ReproBoxCollection + */ + public function map(Closure $mapper): ReproBoxCollection + { + $mapped = []; + foreach ($this->items as $item) { + $mapped[] = $mapper($item); + } + + return new ReproBoxCollection($mapped); + } +} + +describe('Closure Parameter Class-Template Preservation', function () { + describe('Bug: inferTemplatesFromClosures overwriting bound class templates', function () { + test('does not overwrite union TValue when closure accepts base interface (multi-type)', function () { + $collection = new ReproBoxCollection([ + new ReproPrimaryKeyStatement(), + new ReproTextStatement(), + new ReproVarcharStatement(), + ]); + + $filtered = $collection->filter(function (ReproStatement $statement): bool { + return true; + }); + + expect($filtered->items)->toHaveCount(3); + }); + + test('does not overwrite single concrete TValue when closure accepts base interface', function () { + $collection = new ReproBoxCollection([ + new ReproPrimaryKeyStatement(), + ]); + + $filtered = $collection->filter(function (ReproStatement $statement): bool { + return true; + }); + + expect($filtered->items)->toHaveCount(1); + }); + }); + + describe('Regression Safety: method-level template inference & callback contracts', function () { + test('still properly infers method-level template @template R from closure return type', function () { + $collection = new ReproBoxCollection([ + new ReproPrimaryKeyStatement(), + ]); + + $mapped = $collection->map(function (ReproStatement $statement): string { + return 'mapped'; + }); + + expect($mapped)->toBeInstanceOf(ReproBoxCollection::class) + ->and($mapped->items)->toBe(['mapped']) + ; + }); + + test('still rejects incompatible argument passed to closure parameter', function () { + $collection = new ReproBoxCollection([ + new ReproTextStatement(), + ]); + + expect(fn () => $collection->filter(function (ReproPrimaryKeyStatement $pk): bool { + return true; + }))->toThrow(\TypeError::class); + }); + }); +}); From a4b97a5a41b64e11838715cb6d31f2adbb0d3eed Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 21 Nov 2026 14:03:05 +0800 Subject: [PATCH 17/25] Enhance ParamChecker, ReturnChecker, TemplateManager, RuntimeTypeChecker, and GenericValidator with improved caching mechanisms, refined template handling, and optimized validation logic for better performance and type safety --- src/Internal/Checker/ParamChecker.php | 146 +++++++++++++++----- src/Internal/Checker/ReturnChecker.php | 55 ++++++-- src/Internal/Generics/TemplateManager.php | 29 ++-- src/Internal/RuntimeTypeChecker.php | 8 +- src/Internal/Validator/GenericValidator.php | 84 +++++++++-- 5 files changed, 249 insertions(+), 73 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 76545d83..3741d2a2 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -157,11 +157,20 @@ final class ParamChecker */ private static array $templateBoundPlanCache = []; + /** + * In-memory 3D cache for substituted non-conditional parameter types: + * [$cacheKey][$sig] => TypeNode + * + * @var array> + */ + private static array $substitutedParamCache = []; + /** * Resets internal caches. Useful for test isolation. */ public static function reset(): void { + self::$substitutedParamCache = []; self::$effectiveFunctionCache = []; self::$noParamContractCache = []; self::$functionKindCache = []; @@ -283,9 +292,12 @@ public static function checkParams( self::preInferGenericTemplates($contract['types'], $vars, $effectiveFunction, $thisObj, $allTemplates, $classTemplates); } - $boundTemplates = (\count($allTemplates) > 0) - ? TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates) - : []; + $boundTemplates = []; + if (\count($allTemplates) > 0) { + $boundTemplates = ($thisObj !== null && \count($classTemplates) === 0) + ? (TemplateManager::getTopCallFrame($effectiveFunction) ?? []) + : TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates); + } $declaredTemplates = $allTemplates; $baseTypes = self::resolveBaseTypes($contract['types'], $effectiveFunction, $thisObj, $aliases, $paramsAreDynamic); @@ -305,7 +317,8 @@ public static function checkParams( $thisOrClass, $sensitiveParams, $hasMethodTemplates, - $functionKind === self::KIND_CONSTRUCT + $functionKind === self::KIND_CONSTRUCT, + $contract['hasCrossReferencedBounds'] ?? true ); } @@ -537,18 +550,32 @@ private static function validateAllParameters( object|string|null $thisOrClass = null, array $sensitiveParams = [], bool $hasMethodTemplates = false, - bool $isConstructor = false + bool $isConstructor = false, + bool $hasCrossReferencedBounds = true ): ?ErrorMessage { + $templateCount = \count($allTemplates); + $hasClassTemplates = \count($classTemplates) > 0; + $isFirstParam = true; + foreach ($contractTypes as $paramName => $_) { if (! isset($vars[$paramName]) && ! \array_key_exists($paramName, $vars)) { continue; } - $currentBoundTemplates = (\count($allTemplates) > 0) - ? (($thisObj !== null && ! $hasMethodTemplates && ! $isConstructor) - ? TemplateManager::getInstanceBindingsFast($thisObj) - : TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates)) - : $boundTemplates; + if ($isFirstParam) { + $currentBoundTemplates = $boundTemplates; + $isFirstParam = false; + } elseif ($templateCount > 0) { + if ($thisObj !== null && ! $hasMethodTemplates && ! $isConstructor) { + $currentBoundTemplates = TemplateManager::getInstanceBindingsFast($thisObj); + } elseif ($thisObj !== null && ! $hasClassTemplates) { + $currentBoundTemplates = TemplateManager::getTopCallFrame($effectiveFunction) ?? []; + } else { + $currentBoundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates); + } + } else { + $currentBoundTemplates = $boundTemplates; + } $isSensitive = $sensitiveParams[$paramName] ?? false; @@ -574,7 +601,7 @@ private static function validateAllParameters( } } - if (\count($allTemplates) > 0) { + if ($hasCrossReferencedBounds && $templateCount > 0) { return self::validateCrossReferencedTemplateBounds( $contractTypes, $baseTypes, @@ -1122,7 +1149,7 @@ private static function inferTemplatesFromShapes( array $classTemplates = [] ): void { foreach ($types as $paramName => $typeNode) { - if (isset($vars[$paramName])) { + if (isset($vars[$paramName]) && (\is_array($vars[$paramName]) || \is_object($vars[$paramName]))) { self::inferShapeNodeTemplates($typeNode, $vars[$paramName], $effectiveFunction, $thisObj, $templates, $classTemplates); } } @@ -1326,30 +1353,23 @@ private static function inferArrayTemplatesFromAllElements( $inferredKeyType = null; $inferredValType = null; - $hasEmptyValArray = false; foreach ($sampleItems as $key => $item) { if ($keyTName !== null) { $keyType = TemplateManager::inferTypeFromValue($key); - $inferredKeyType = ($inferredKeyType === null) ? $keyType : self::unifyTypes($inferredKeyType, $keyType); + if ($inferredKeyType === null) { + $inferredKeyType = $keyType; + } elseif ($keyType !== $inferredKeyType) { + $inferredKeyType = self::unifyTypes($inferredKeyType, $keyType); + } } if ($valTName !== null) { - if ($item === []) { - $hasEmptyValArray = true; - - continue; - } $valType = TemplateManager::inferTypeFromValue($item); - $inferredValType = ($inferredValType === null) ? $valType : self::unifyTypes($inferredValType, $valType); - } - } - - if ($valTName !== null && $hasEmptyValArray) { - $emptyListNode = TemplateManager::inferTypeFromValue([]); - if ($inferredValType === null) { - $inferredValType = $emptyListNode; - } elseif (! self::isCollectionTypeNode($inferredValType)) { - $inferredValType = self::unifyTypes($inferredValType, $emptyListNode); + if ($inferredValType === null) { + $inferredValType = $valType; + } elseif ($valType !== $inferredValType) { + $inferredValType = self::unifyTypes($inferredValType, $valType); + } } } @@ -1650,12 +1670,9 @@ private static function inferTemplatesFromGenericObjects( array $classTemplates = [] ): void { foreach ($types as $paramName => $typeNode) { - if (! isset($vars[$paramName])) { - continue; + if (isset($vars[$paramName]) && (\is_object($vars[$paramName]) || \is_array($vars[$paramName]))) { + self::inferGenericObjectNode($typeNode, $vars[$paramName], $effectiveFunction, $thisObj, $templates, $classTemplates); } - - $value = $vars[$paramName]; - self::inferGenericObjectNode($typeNode, $value, $effectiveFunction, $thisObj, $templates, $classTemplates); } } @@ -2101,7 +2118,9 @@ private static function validateSingleParam( return self::resolveTemplateParam($typeNode, $val, $paramName, $effectiveFunction, $thisObj, $templates, $registry, $classTemplates, $thisOrClass); } + $hadConditional = false; if (ConditionalChecker::containsConditional($typeNode)) { + $hadConditional = true; $typeNode = ConditionalChecker::resolve($typeNode, $vars, $boundTemplates, $registry, $effectiveFunction); } @@ -2114,9 +2133,41 @@ private static function validateSingleParam( $shouldSkipTemplateSub = $isBareTemplate || $isClassStringT; if (! $shouldSkipTemplateSub && (\count($boundTemplates) > 0 || \count($declaredTemplates) > 0)) { - $subType = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $declaredTemplates); - if ($subType !== $typeNode) { - $typeNode = SpecialTypeResolver::resolve($subType, $effectiveFunction, $thisObj); + $boundCount = \count($boundTemplates); + $sig = null; + $cacheKey = null; + + if (! $hadConditional && $boundCount <= 5 && ! ($typeNode instanceof IdentifierTypeNode)) { + $cacheKey = $effectiveFunction . '::' . $paramName . ($thisObj !== null ? '@' . $thisObj::class : ''); + if ($boundCount === 0) { + $sig = ''; + } elseif ($boundCount === 1) { + $firstKey = (string) array_key_first($boundTemplates); + $first = $boundTemplates[$firstKey]; + $sig = $firstKey . '=' . ($first instanceof IdentifierTypeNode ? $first->name : (string) $first); + } else { + $sig = ''; + foreach ($boundTemplates as $k => $v) { + $sig .= $k . '=' . ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|'; + } + } + + if (str_contains($sig, 'static') || str_contains($sig, '$this')) { + $sig = null; + } + } + + if ($sig !== null && isset(self::$substitutedParamCache[$cacheKey][$sig])) { + $typeNode = self::$substitutedParamCache[$cacheKey][$sig]; + } else { + $subType = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $declaredTemplates); + if ($subType !== $typeNode) { + $typeNode = SpecialTypeResolver::resolve($subType, $effectiveFunction, $thisObj); + } + + if ($sig !== null && $cacheKey !== null) { + self::$substitutedParamCache[$cacheKey][$sig] = $typeNode; + } } } @@ -2276,6 +2327,8 @@ private static function resolveClassStringTemplate( if (! TemplateManager::isBound($function, $targetObj, $templateName)) { if (! \is_string($val) || ! ClassNameValidator::isValidClassString($val)) { + $redact = $isSensitive || Config::isRedactValuesEnabled(); + return ErrorFactory::createError($function . '(): Argument $' . $paramName . ' must be a valid class-string, ' . TypeFormatter::formatGivenValue($val, $redact) . ' given'); } @@ -2296,6 +2349,7 @@ private static function resolveClassStringTemplate( $resolvedBound = SpecialTypeResolver::resolve($boundNode, $function, $thisObj); if (! self::checkClassStringSatisfiesBound($val, $resolvedBound)) { + $redact = $isSensitive || Config::isRedactValuesEnabled(); $boundDisplay = (string) $resolvedBound; $displayVal = $redact ? 'string given' : "'" . $val . "' given"; @@ -2310,6 +2364,7 @@ private static function resolveClassStringTemplate( $expectedTypeNode = TemplateManager::getBoundType($function, $targetObj, $templateName); if ($expectedTypeNode !== null) { if (! \is_string($val) || ! self::checkClassStringSatisfiesBound($val, $expectedTypeNode)) { + $redact = $isSensitive || Config::isRedactValuesEnabled(); $valStr = TypeFormatter::formatGivenValue($val, $redact); $targetDisplay = (string) $expectedTypeNode; @@ -2753,6 +2808,23 @@ private static function tryWidenTemplate( */ private static function unifyTypes(TypeNode $type1, TypeNode $type2): TypeNode { + if ($type1 === $type2) { + return $type1; + } + + if ($type1 instanceof IdentifierTypeNode && $type2 instanceof IdentifierTypeNode && $type1->name === $type2->name) { + return $type1; + } + + if ($type1 instanceof UnionTypeNode && $type2 instanceof IdentifierTypeNode) { + $t2Name = $type2->name; + foreach ($type1->types as $member) { + if ($member instanceof IdentifierTypeNode && $member->name === $t2Name) { + return $type1; + } + } + } + if ((string) $type1 === (string) $type2) { return $type1; } diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index f5546f49..52ba80eb 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -338,6 +338,16 @@ private static function evaluateReturn( if ($err !== null) { return $err; } + + if ($thisObj !== null) { + return $value; + } + } + + if ($thisObj !== null && $returnTypeNode instanceof IdentifierTypeNode && strtolower($returnTypeNode->name) === 'static') { + if ($value instanceof $thisObj) { + return $value; + } } $hasGenerics = (\count($templates) > 0); @@ -382,17 +392,30 @@ private static function evaluateReturn( return $value; } - $boundTemplates = ($thisObj !== null && ($contract['templates'] ?? []) === []) - ? TemplateManager::getInstanceBindingsFast($thisObj) - : TemplateManager::getBoundTemplates($function, $thisObj, $templates); + $hasClassTemplates = ($contract['classTemplates'] ?? []) !== []; + $hasMethodTemplates = ($contract['templates'] ?? []) !== []; + + if ($thisObj !== null && ! $hasMethodTemplates) { + $boundTemplates = $hasClassTemplates ? TemplateManager::getInstanceBindingsFast($thisObj) : []; + } elseif ($thisObj !== null && ! $hasClassTemplates) { + $boundTemplates = TemplateManager::getTopCallFrame($function) ?? []; + } else { + $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + } $isDynamicReturn = $contract['returnIsDynamic'] ?? (str_contains((string) $returnTypeNode, 'static') || str_contains((string) $returnTypeNode, '$this')); $sig = null; + $cacheFunc = null; $boundCount = \count($boundTemplates); - if ($boundCount > 0 && $boundCount <= 2 && ! $hasConditionals && \count($aliases) === 0 && ! $isDynamicReturn) { - if ($boundCount === 1) { + + if ($boundCount <= 5 && ! $hasConditionals && ($thisObj !== null || ! $isDynamicReturn)) { + $cacheFunc = ($isDynamicReturn && $thisObj !== null) ? ($function . '@' . $thisObj::class) : $function; + + if ($boundCount === 0) { + $sig = ''; + } elseif ($boundCount === 1) { $firstKey = (string) array_key_first($boundTemplates); $first = $boundTemplates[$firstKey]; $sig = $firstKey . '=' . ($first instanceof IdentifierTypeNode ? $first->name : (string) $first); @@ -405,13 +428,15 @@ private static function evaluateReturn( if (str_contains($sig, 'static') || str_contains($sig, '$this')) { $sig = null; - } elseif (isset(self::$substitutedReturnCache[$function][$sig])) { - $resolvedType = self::$substitutedReturnCache[$function][$sig]; + } elseif (isset(self::$substitutedReturnCache[$cacheFunc][$sig])) { + $resolvedType = self::$substitutedReturnCache[$cacheFunc][$sig]; } } if (! isset($resolvedType)) { - $resolvedType = SpecialTypeResolver::resolve($returnTypeNode, $function, $thisObj); + $resolvedType = $isDynamicReturn + ? SpecialTypeResolver::resolve($returnTypeNode, $function, $thisObj) + : $returnTypeNode; if ($resolvedType instanceof IdentifierTypeNode && isset($aliases[$resolvedType->name])) { $resolvedType = $aliases[$resolvedType->name]; @@ -421,23 +446,25 @@ private static function evaluateReturn( $resolvedType = ConditionalChecker::resolve($resolvedType, $vars, $boundTemplates, $registry, $function); } - if (\count($boundTemplates) === 0 && \count($templates) > 0 && ! $hasConditionals && $thisObj === null) { + if ($boundCount === 0 && \count($templates) > 0 && ! $hasConditionals && $thisObj === null) { $resolvedType = self::$unboundReturnCache[$function] ??= SpecialTypeResolver::resolve( TemplateSubstitutor::substitute($returnTypeNode, [], $templates), $function, null ); - } elseif (\count($boundTemplates) > 0 || \count($templates) > 0) { - $resolvedType = TemplateSubstitutor::substitute($resolvedType, $boundTemplates, $templates); - $resolvedType = SpecialTypeResolver::resolve($resolvedType, $function, $thisObj); + } elseif ($boundCount > 0 || \count($templates) > 0) { + $subType = TemplateSubstitutor::substitute($resolvedType, $boundTemplates, $templates); + $resolvedType = ($isDynamicReturn || $subType !== $resolvedType) + ? SpecialTypeResolver::resolve($subType, $function, $thisObj) + : $subType; } if (ConditionalChecker::containsConditional($resolvedType)) { $resolvedType = ConditionalChecker::resolve($resolvedType, $vars, $boundTemplates, $registry, $function); } - if ($sig !== null) { - self::$substitutedReturnCache[$function][$sig] = $resolvedType; + if ($sig !== null && $cacheFunc !== null) { + self::$substitutedReturnCache[$cacheFunc][$sig] = $resolvedType; } } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index fb330cd5..be43e32b 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -977,18 +977,23 @@ public static function getBoundTemplates(string $function, object|string|null $t $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; if ($thisObj !== null) { - $isCtor = str_ends_with(strtolower($function), '::__construct'); - if ($isCtor) { - self::ensureInstanceInherited($thisObj); - $bindings = self::$instanceTemplateBindings[$thisObj] ?? []; - } else { - $bindings = self::getInstanceBindingsFast($thisObj); - } + $className = $thisObj::class; + [$classHierarchyTemplates] = self::hierarchyTemplatesForClass($className); + + if ($classHierarchyTemplates !== []) { + $isCtor = \strlen($function) > 13 && substr_compare($function, '::__construct', -13, 13, true) === 0; + if ($isCtor) { + self::ensureInstanceInherited($thisObj); + $bindings = self::$instanceTemplateBindings[$thisObj] ?? []; + } else { + $bindings = self::getInstanceBindingsFast($thisObj); + } - $methodTemplates = self::getMethodTemplates($function); - if ($methodTemplates !== []) { - foreach ($methodTemplates as $methodTName => $_) { - unset($bindings[$methodTName]); + $methodTemplates = self::getMethodTemplates($function); + if ($methodTemplates !== []) { + foreach ($methodTemplates as $methodTName => $_) { + unset($bindings[$methodTName]); + } } } } else { @@ -3601,7 +3606,7 @@ private static function hasCallFrame(string $function): bool /** * @return array|null */ - private static function getTopCallFrame(string $function): ?array + public static function getTopCallFrame(string $function): ?array { if (! isset(self::$callStackBindings[$function]) || self::$callStackBindings[$function] === []) { return null; diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 30c7483c..4252605a 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -932,8 +932,12 @@ public static function setupScope(string $function, array $vars, object|string|n if ($hasMethodTemplates) { $cleaner = new ScopeCleaner($effectiveFunction); - $allTemplates = [...$contract['classTemplates'], ...$contract['templates']]; - $cleaner->boundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $allTemplates); + if ($thisObj !== null && $contract['classTemplates'] === []) { + $cleaner->boundTemplates = TemplateManager::getTopCallFrame($effectiveFunction) ?? []; + } else { + $allTemplates = [...$contract['classTemplates'], ...$contract['templates']]; + $cleaner->boundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $allTemplates); + } return $cleaner; } diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index 44e15c23..af97c5d9 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -85,6 +85,11 @@ final class GenericValidator implements TypeValidatorInterface */ private static array $maskOfCache = []; + /** + * @var array> + */ + private static array $classStringBoundCache = []; + public static function reset(): void { self::$compiledGenericCache = null; @@ -92,6 +97,7 @@ public static function reset(): void self::$enumKeyCache = []; self::$enumValueCache = []; self::$maskOfCache = []; + self::$classStringBoundCache = []; } /** @@ -744,6 +750,33 @@ private function validateKeyValueTypeArray( $isComplexObjectGeneric = ($valTypeNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower((string) $valTypeNode->type)])); + if ($keyIsArrayKey && ! $isComplexObjectGeneric) { + return CollectionElementValidator::validateElements( + $value, + $valTypeNode, + $context, + $registry, + isList: false, + isSensitive: $isSensitive, + count: $count, + ); + } + + $keyFast = $keyIsArrayKey ? 3 : ($keyTypeNode instanceof IdentifierTypeNode ? match ($keyTypeNode->name) { + 'int', 'integer' => 1, + 'string' => 2, + default => 0, + } : 0); + + $valFast = $valIsMixed ? 6 : ($valTypeNode instanceof IdentifierTypeNode ? match ($valTypeNode->name) { + 'int', 'integer' => 1, + 'string' => 2, + 'bool', 'boolean' => 3, + 'float', 'double' => 4, + 'object' => 5, + default => 0, + } : 0); + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { $keys = array_keys($value); $sampleKeys = [$keys[0], $keys[$count - 1]]; @@ -753,15 +786,30 @@ private function validateKeyValueTypeArray( } foreach ($sampleKeys as $k) { - if (! $keyIsArrayKey) { + $keyOk = match ($keyFast) { + 3 => true, + 1 => \is_int($k), + 2 => \is_string($k), + default => false, + }; + if (! $keyOk) { $err = $registry->validate($k, $keyTypeNode, ''); if ($err !== null) { return ErrorFactory::createError($context . ' key' . $err->getMessage()); } } - if (! $valIsMixed) { - $v = $value[$k]; + $v = $value[$k]; + $valOk = match ($valFast) { + 6 => true, + 1 => \is_int($v), + 2 => \is_string($v), + 3 => \is_bool($v), + 4 => \is_float($v) || \is_int($v), + 5 => \is_object($v), + default => false, + }; + if (! $valOk) { $err = $isComplexObjectGeneric ? $this->validateObjectGeneric($v, $valTypeNode, '', $isSensitive) : $registry->validate($v, $valTypeNode, '', $isSensitive); @@ -776,15 +824,29 @@ private function validateKeyValueTypeArray( } foreach ($value as $k => $v) { - if (! $keyIsArrayKey) { + $keyOk = match ($keyFast) { + 3 => true, + 1 => \is_int($k), + 2 => \is_string($k), + default => false, + }; + if (! $keyOk) { $err = $registry->validate($k, $keyTypeNode, ''); if ($err !== null) { return ErrorFactory::createError($context . ' key' . $err->getMessage()); } } - if (! $valIsMixed) { - $v = $value[$k]; + $valOk = match ($valFast) { + 6 => true, + 1 => \is_int($v), + 2 => \is_string($v), + 3 => \is_bool($v), + 4 => \is_float($v) || \is_int($v), + 5 => \is_object($v), + default => false, + }; + if (! $valOk) { $err = $isComplexObjectGeneric ? $this->validateObjectGeneric($v, $valTypeNode, '', $isSensitive) : $registry->validate($v, $valTypeNode, '', $isSensitive); @@ -868,10 +930,12 @@ private function validateClassString(mixed $value, GenericTypeNode $node, string private function validateClassStringBound(string $value, TypeNode $targetNode, string $context, bool $isSensitive = false): ?ErrorMessage { - $redact = $isSensitive || Config::isRedactValuesEnabled(); - if ($targetNode instanceof IdentifierTypeNode) { $targetName = $targetNode->name; + if (isset(self::$classStringBoundCache[$targetName][$value])) { + return null; + } + $lower = strtolower($targetName); if ($lower === 'object' || $lower === 'mixed') { return null; @@ -879,10 +943,13 @@ private function validateClassStringBound(string $value, TypeNode $targetNode, s if (class_exists($targetName) || interface_exists($targetName) || trait_exists($targetName) || enum_exists($targetName)) { if (! is_a($value, $targetName, allow_string: true)) { + $redact = $isSensitive || Config::isRedactValuesEnabled(); $valDisplay = $redact ? 'string given' : "'$value' given"; return ErrorFactory::createError($context . ' must be a class-string of ' . $targetName . ", $valDisplay"); } + + self::$classStringBoundCache[$targetName][$value] = true; } return null; @@ -895,6 +962,7 @@ private function validateClassStringBound(string $value, TypeNode $targetNode, s } } + $redact = $isSensitive || Config::isRedactValuesEnabled(); $valDisplay = $redact ? 'string given' : "'$value' given"; return ErrorFactory::createError($context . ' must be a class-string of ' . (string) $targetNode . ", $valDisplay"); From 3a656c654084e9c0f439f949245089f39c785b02 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 22 Nov 2026 13:18:29 +0800 Subject: [PATCH 18/25] Refactor type validation logic and enhance class-string handling - Changed the visibility of `validClassStringCache` in ClassNameValidator to public for better accessibility. - Updated CollectionElementValidator to utilize RuntimeTypeChecker for hybrid validation checks instead of Config. - Added support for new types in CollectionElementValidator: 'object', 'array-key', and 'class-string' with appropriate validation logic. - Enhanced GenericValidator to include detailed array plan handling and improved validation for key-value type arrays. - Updated UnionValidator to streamline type checks and added support for mixed types, arrays, and iterables. - Improved type validation logic in TypeValidatorRegistry to include class-string checks. - Fixed test case to correctly reference TypeError class. --- src/Internal/Ast/FunctionContractInjector.php | 218 ++++++- src/Internal/Checker/ConditionalChecker.php | 82 ++- src/Internal/Checker/InlineChecker.php | 16 +- src/Internal/Checker/MemberAssignChecker.php | 117 ++++ src/Internal/Checker/ParamChecker.php | 446 ++++++++++++-- src/Internal/Checker/ReturnChecker.php | 64 +- src/Internal/Docblock/DocblockParser.php | 59 +- src/Internal/Generics/TemplateManager.php | 114 ++-- src/Internal/RuntimeTypeChecker.php | 554 +++++++++++++++++- src/Internal/Util/ClassNameValidator.php | 2 +- .../Validator/CollectionElementValidator.php | 73 ++- src/Internal/Validator/GenericValidator.php | 276 ++++++++- .../Validator/TypeValidatorRegistry.php | 6 +- src/Internal/Validator/UnionValidator.php | 141 +++-- ...losureParameterTemplateOverwritingTest.php | 2 +- 15 files changed, 1903 insertions(+), 267 deletions(-) diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 20b3e7e6..5810d575 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -211,7 +211,8 @@ public static function inject( $hasParamOut ? $byRefParams : [], $hasSelfOut, $hasParam, - $trustedParamTypes + $trustedParamTypes, + $useDynamicMethodKey ) : self::wrapNonGeneratorReturns( $node->stmts, @@ -226,7 +227,9 @@ public static function inject( $classContext, $returnTypeNode, $currentFile, - $trustedParamTypes + $trustedParamTypes, + $useDynamicMethodKey, + ! $isMagicGet && ! $isMagicCall ); } @@ -576,8 +579,11 @@ private function disqualifyTarget(Node $target): void return $visitor->unmutated; } - public static function buildSelfOutCheckStmt(Node\Expr $thisArg, bool $needsReturnVars = false): Node\Stmt\Expression - { + public static function buildSelfOutCheckStmt( + Node\Expr $thisArg, + bool $needsReturnVars = false, + bool $useDynamicMethodKey = false + ): Node\Stmt\If_ { $varsArg = $needsReturnVars ? new Node\Expr\Variable('_typephpArgs') : new Node\Expr\Array_(); @@ -591,10 +597,73 @@ public static function buildSelfOutCheckStmt(Node\Expr $thisArg, bool $needsRetu ] ); - $stmt = new Node\Stmt\Expression($checkCall); - $stmt->setAttribute('typephp_injected', true); + $cacheKeyExpr = $useDynamicMethodKey + ? new Node\Expr\BinaryOp\Concat( + new Node\Expr\BinaryOp\Concat( + new Node\Expr\ClassConstFetch(new Node\Name('static'), 'class'), + new Node\Scalar\String_('::') + ), + new Node\Scalar\MagicConst\Function_() + ) + : new Node\Scalar\MagicConst\Method(); + + $noSelfOutFetch = new Node\Expr\StaticPropertyFetch( + new Node\Name\FullyQualified('TypePHP\Internal\Checker\SelfOutChecker'), + 'noSelfOutContractCache' + ); + $noSelfOutFetch->setAttribute('typephp_checked', true); + + $ifStmt = new Node\Stmt\If_( + new Node\Expr\BooleanNot( + new Node\Expr\Isset_([ + new Node\Expr\ArrayDimFetch($noSelfOutFetch, $cacheKeyExpr), + ]) + ), + ['stmts' => [new Node\Stmt\Expression($checkCall)]] + ); + $ifStmt->setAttribute('typephp_injected', true); - return $stmt; + return $ifStmt; + } + + public static function buildGuardedTernaryReturnExpr( + Node\Expr $exprToWrap, + Node\Expr $thisArg, + bool $needsReturnVars = false, + bool $useDynamicMethodKey = false, + ?int $line = null + ): Node\Expr\Ternary { + $cacheKeyExpr = $useDynamicMethodKey + ? new Node\Expr\BinaryOp\Concat( + new Node\Expr\BinaryOp\Concat( + new Node\Expr\ClassConstFetch(new Node\Name('static'), 'class'), + new Node\Scalar\String_('::') + ), + new Node\Scalar\MagicConst\Function_() + ) + : new Node\Scalar\MagicConst\Method(); + + $noReturnFetch = new Node\Expr\StaticPropertyFetch( + new Node\Name\FullyQualified('TypePHP\Internal\Checker\ReturnChecker'), + 'noReturnContractCache' + ); + $noReturnFetch->setAttribute('typephp_checked', true); + + $retVar = new Node\Expr\Variable('__typephpRet'); + $assignAndFalse = new Node\Expr\BinaryOp\BooleanAnd( + new Node\Expr\Assign($retVar, $exprToWrap), + new Node\Expr\ConstFetch(new Node\Name('false')) + ); + + $fastSkipCond = new Node\Expr\BinaryOp\BooleanOr( + $assignAndFalse, + new Node\Expr\Isset_([new Node\Expr\ArrayDimFetch($noReturnFetch, $cacheKeyExpr)]) + ); + + $checkCall = self::buildReturnCheckCall(new Node\Expr\Variable('__typephpRet'), $thisArg, $needsReturnVars); + $slowPath = self::buildTernaryReturnExpr($checkCall, $line); + + return new Node\Expr\Ternary($fastSkipCond, new Node\Expr\Variable('__typephpRet'), $slowPath); } /** @@ -999,7 +1068,8 @@ private static function buildParamWrappers( $expr = new Node\Stmt\Expression($assignExpr); $expr->setAttribute('typephp_injected', true); - $wrappers[] = $expr; + + $bodyStmts = [$expr]; $isReadonlyParam = ($param->flags & Node\Stmt\Class_::MODIFIER_READONLY) !== 0; $isReadonly = $isReadonlyParam || $isReadonlyClass; @@ -1012,7 +1082,30 @@ private static function buildParamWrappers( ) ); $propAssign->setAttribute('typephp_injected', true); - $wrappers[] = $propAssign; + $bodyStmts[] = $propAssign; + } + + $guardCond = null; + if ($wrapperMethod === 'wrapIterable' && self::paramMayBeArray($param)) { + $guardCond = new Node\Expr\Instanceof_( + new Node\Expr\Variable($paramName), + new Node\Name\FullyQualified('Traversable') + ); + } elseif ($wrapperMethod === 'wrapCallable' && self::paramMayBeNull($param)) { + $guardCond = new Node\Expr\BinaryOp\NotIdentical( + new Node\Expr\Variable($paramName), + new Node\Expr\ConstFetch(new Node\Name('null')) + ); + } + + if ($guardCond !== null) { + $ifStmt = new Node\Stmt\If_($guardCond, ['stmts' => $bodyStmts]); + $ifStmt->setAttribute('typephp_injected', true); + $wrappers[] = $ifStmt; + } else { + foreach ($bodyStmts as $stmt) { + $wrappers[] = $stmt; + } } } } @@ -1020,6 +1113,58 @@ private static function buildParamWrappers( return $wrappers; } + private static function paramMayBeNull(Node\Param $param): bool + { + if ($param->default instanceof Node\Expr\ConstFetch && strtolower($param->default->name->toString()) === 'null') { + return true; + } + + $type = $param->type; + if ($type === null || $type instanceof Node\NullableType) { + return true; + } + + if ($type instanceof Node\Identifier) { + return \in_array(strtolower($type->name), ['mixed', 'null'], true); + } + + if ($type instanceof Node\UnionType) { + foreach ($type->types as $t) { + if ($t instanceof Node\Identifier && \in_array(strtolower($t->name), ['mixed', 'null'], true)) { + return true; + } + } + } + + return false; + } + + private static function paramMayBeArray(Node\Param $param): bool + { + $type = $param->type; + if ($type === null) { + return true; + } + + while ($type instanceof Node\NullableType) { + $type = $type->type; + } + + if ($type instanceof Node\Identifier) { + return \in_array(strtolower($type->name), ['array', 'iterable', 'mixed'], true); + } + + if ($type instanceof Node\UnionType) { + foreach ($type->types as $t) { + if ($t instanceof Node\Identifier && \in_array(strtolower($t->name), ['array', 'iterable', 'mixed'], true)) { + return true; + } + } + } + + return false; + } + private static function isCallableCandidate(Node\Param $param, string $docText): bool { if ( @@ -1300,7 +1445,8 @@ private static function wrapGeneratorReturns( array $byRefParams = [], bool $hasSelfOut = false, bool $hasScope = false, - array $trustedParamTypes = [] + array $trustedParamTypes = [], + bool $useDynamicMethodKey = false ): array { $canEliminate = $functionNode !== null && ! $hasMethodTemplates @@ -1328,7 +1474,8 @@ private static function wrapGeneratorReturns( $needsReturnVars, $byRefParams, $hasSelfOut, - $trustedParamTypes + $trustedParamTypes, + $useDynamicMethodKey ) extends NodeVisitorAbstract { /** * @param array{key: ?TypeNode, value: ?TypeNode, send: ?TypeNode, return: ?TypeNode}|null $genContract @@ -1344,7 +1491,8 @@ public function __construct( private bool $needsReturnVars, private array $byRefParams, private bool $hasSelfOut, - private array $trustedParamTypes + private array $trustedParamTypes, + private bool $useDynamicMethodKey ) { } @@ -1458,7 +1606,7 @@ public function enterNode(Node $n): int|Node|array|null $exitStmts = []; if ($this->hasSelfOut) { - $exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars); + $exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars, $this->useDynamicMethodKey); } $paramOutStmts = $this->byRefParams !== [] @@ -1517,7 +1665,7 @@ public function enterNode(Node $n): int|Node|array|null if (! $lastStmt instanceof Node\Stmt\Return_ && ! ($lastStmt instanceof Node\Stmt\Expression && $lastStmt->expr instanceof Node\Expr\Throw_)) { $exitStmts = []; if ($hasSelfOut) { - $exitStmts[] = self::buildSelfOutCheckStmt($thisArg, $needsReturnVars); + $exitStmts[] = self::buildSelfOutCheckStmt($thisArg, $needsReturnVars, $useDynamicMethodKey); } $paramOutStmts = $byRefParams !== [] @@ -1586,7 +1734,9 @@ private static function wrapNonGeneratorReturns( ?array $classContext = null, ?TypeNode $returnTypeNode = null, string $currentFile = '', - array $trustedParamTypes = [] + array $trustedParamTypes = [], + bool $useDynamicMethodKey = false, + bool $canGuardReturnCache = true ): array { self::tagPrecedingAssignments($stmts); @@ -1603,7 +1753,9 @@ private static function wrapNonGeneratorReturns( $classContext, $returnTypeNode, $currentFile, - $trustedParamTypes + $trustedParamTypes, + $useDynamicMethodKey, + $canGuardReturnCache ) extends NodeVisitorAbstract { /** * @param array $byRefParams @@ -1622,7 +1774,9 @@ public function __construct( private ?array $classContext, private ?TypeNode $returnTypeNode, private string $currentFile, - private array $trustedParamTypes + private array $trustedParamTypes, + private bool $useDynamicMethodKey, + private bool $canGuardReturnCache ) { } @@ -1658,7 +1812,7 @@ public function enterNode(Node $n): int|array|null $exitStmts = []; if ($this->hasSelfOut) { - $exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars); + $exitStmts[] = FunctionContractInjector::buildSelfOutCheckStmt($this->thisArg, $this->needsReturnVars, $this->useDynamicMethodKey); } $paramOutStmts = $this->byRefParams !== [] @@ -1696,15 +1850,25 @@ public function enterNode(Node $n): int|array|null return [...$exitStmts, ...$voidGuardStmts]; } - $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); - if ($this->isByRefReturn) { + $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); $byRefGuardStmts = FunctionContractInjector::buildByRefReturnGuard($checkCall, $n, $n->getStartLine()); return [...$exitStmts, ...$byRefGuardStmts]; } - $n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $n->getStartLine()); + if ($this->canGuardReturnCache) { + $n->expr = FunctionContractInjector::buildGuardedTernaryReturnExpr( + $exprToWrap, + $this->thisArg, + $this->needsReturnVars, + $this->useDynamicMethodKey, + $n->getStartLine() + ); + } else { + $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); + $n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $n->getStartLine()); + } return $exitStmts !== [] ? [...$exitStmts, $n] : null; } @@ -1720,7 +1884,7 @@ public function enterNode(Node $n): int|array|null if (! $lastStmt instanceof Node\Stmt\Return_ && ! ($lastStmt instanceof Node\Stmt\Expression && $lastStmt->expr instanceof Node\Expr\Throw_)) { $exitStmts = []; if ($hasSelfOut) { - $exitStmts[] = self::buildSelfOutCheckStmt($thisArg, $needsReturnVars); + $exitStmts[] = self::buildSelfOutCheckStmt($thisArg, $needsReturnVars, $useDynamicMethodKey); } $paramOutStmts = $byRefParams !== [] @@ -1748,7 +1912,15 @@ public function enterNode(Node $n): int|array|null $newStmts = [...$newStmts, ...$exitStmts, ...$byRefGuardStmts]; } else { $fallbackLine = $lastStmt instanceof Node\Stmt ? $lastStmt->getStartLine() : null; - $ternaryExpr = self::buildTernaryReturnExpr($checkCall, $fallbackLine); + $ternaryExpr = $canGuardReturnCache + ? self::buildGuardedTernaryReturnExpr( + new Node\Expr\ConstFetch(new Node\Name('null')), + $thisArg, + $needsReturnVars, + $useDynamicMethodKey, + $fallbackLine + ) + : self::buildTernaryReturnExpr($checkCall, $fallbackLine); $retStmt = new Node\Stmt\Return_($ternaryExpr); $retStmt->setAttribute('typephp_injected', true); diff --git a/src/Internal/Checker/ConditionalChecker.php b/src/Internal/Checker/ConditionalChecker.php index 89f81f7e..de728c44 100644 --- a/src/Internal/Checker/ConditionalChecker.php +++ b/src/Internal/Checker/ConditionalChecker.php @@ -23,9 +23,12 @@ use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use ReflectionClass; use Throwable; +use Traversable; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Resolver\HierarchyResolver; +use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Validator\TypeValidatorRegistry; /** @@ -291,8 +294,83 @@ public static function resolveParameterConditional( $paramValue = self::resolveRenamedParamValue($function, $paramName, $vars); } - $targetErr = $registry->validate($paramValue, $node->targetType, 'condition'); - $isTargetMatch = ($targetErr === null); + $targetType = $node->targetType; + $isTargetMatch = null; + + if ($targetType instanceof IdentifierTypeNode) { + $tName = $targetType->name; + $tLower = strtolower($tName); + $isTargetMatch = match ($tLower) { + 'null' => $paramValue === null, + 'int', 'integer' => \is_int($paramValue), + 'string' => \is_string($paramValue), + 'bool', 'boolean' => \is_bool($paramValue), + 'true' => $paramValue === true, + 'false' => $paramValue === false, + 'float', 'double' => \is_float($paramValue) || \is_int($paramValue), + 'array' => \is_array($paramValue), + 'list' => \is_array($paramValue) && ($paramValue === [] || array_is_list($paramValue)), + 'object' => \is_object($paramValue), + 'iterable' => is_iterable($paramValue), + 'scalar' => \is_scalar($paramValue), + 'array-key' => \is_int($paramValue) || \is_string($paramValue), + 'mixed' => true, + default => (! SpecialTypeResolver::isBuiltInTypeKeyword($tName) && ClassNameValidator::isValid($tName) && (class_exists($tName, false) || interface_exists($tName, false))) + ? (\is_object($paramValue) && ($paramValue instanceof $tName)) + : null, + }; + } elseif ($targetType instanceof GenericTypeNode) { + $gBase = strtolower((string) $targetType->type); + if ($gBase === 'list' || $gBase === 'non-empty-list') { + if (! \is_array($paramValue)) { + $isTargetMatch = false; + } + } elseif ($gBase === 'array' || $gBase === 'non-empty-array' || $gBase === 'iterable' || $gBase === 'traversable' || $gBase === 'iterator' || $gBase === 'generator') { + if (! \is_array($paramValue) && ! ($paramValue instanceof Traversable)) { + $isTargetMatch = false; + } elseif ($gBase === 'array' && \is_array($paramValue)) { + $genericCount = \count($targetType->genericTypes); + if ($genericCount === 0) { + $isTargetMatch = true; + } elseif ($genericCount === 1) { + $gt0 = $targetType->genericTypes[0]; + if ($gt0 instanceof IdentifierTypeNode && \in_array(strtolower($gt0->name), ['mixed', 't', 'tvalue', 'v', 'value', 'telement'], true)) { + $isTargetMatch = true; + } + } else { + $gt0 = $targetType->genericTypes[0]; + $gt1 = $targetType->genericTypes[1]; + if ( + $gt0 instanceof IdentifierTypeNode + && $gt1 instanceof IdentifierTypeNode + && \in_array(strtolower($gt0->name), ['array-key', 'mixed', 'tkey', 'key', 'k'], true) + && \in_array(strtolower($gt1->name), ['mixed', 'tvalue', 'v', 'value', 't'], true) + ) { + $isTargetMatch = true; + } + } + } + } elseif ($gBase === 'int' || $gBase === 'integer' || $gBase === 'int-mask' || $gBase === 'int-mask-of') { + if (! \is_int($paramValue)) { + $isTargetMatch = false; + } + } elseif ($gBase === 'class-string') { + if (! \is_string($paramValue)) { + $isTargetMatch = false; + } + } elseif ($gBase !== 'key-of' && $gBase !== 'value-of') { + $gClass = (string) $targetType->type; + if (! \is_object($paramValue) || ! ($paramValue instanceof $gClass)) { + $isTargetMatch = false; + } + } + } + + if ($isTargetMatch === null) { + $targetErr = $registry->validate($paramValue, $targetType, 'condition'); + $isTargetMatch = ($targetErr === null); + } + if ($node->negated) { $isTargetMatch = ! $isTargetMatch; } diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 3ccd9cb4..742ebc07 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -93,11 +93,19 @@ final class InlineChecker */ private static ?\WeakMap $instancePropertyTypeCache = null; + /** + * In-memory 3D cache for file-resolved TypeNode ASTs: [$file][$namespace][$normalized] => TypeNode. + * + * @var array>> + */ + private static array $resolvedFileTypeCache = []; + /** * Resets internal type node and function caches. Useful for test isolation. */ public static function reset(): void { + self::$resolvedFileTypeCache = []; self::$parsedTypeNodeCache = []; self::$resolvedClassContextCache = []; self::$nullPropertyCache = []; @@ -175,7 +183,9 @@ public static function checkVariable( if ($file !== '') { $callerNamespace = self::extractNamespaceFromCaller($caller); - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file, $callerNamespace); + $nsKey = $callerNamespace ?? "\0"; + $typeNode = self::$resolvedFileTypeCache[$file][$nsKey][$normalized] + ??= SpecialTypeResolver::resolveForFile($typeNode, $file, $callerNamespace); } if ($needsContext && $caller !== null) { @@ -260,7 +270,9 @@ public static function validateCollectionElementMutation( if ($file !== '') { $callerNamespace = self::extractNamespaceFromCaller($caller); - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file, $callerNamespace); + $nsKey = $callerNamespace ?? "\0"; + $typeNode = self::$resolvedFileTypeCache[$file][$nsKey][$normalized] + ??= SpecialTypeResolver::resolveForFile($typeNode, $file, $callerNamespace); } if ($needsContext && $caller !== null) { diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 88145d10..4d2e5ff5 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -123,11 +123,26 @@ final class MemberAssignChecker */ public static ?WeakMap $fastObjectContractCache = null; + /** + * @var WeakMap|null + */ + private static ?WeakMap $innerElementContractCache = null; + /** * Resets the cached reflection property and element contract registries. */ public static function reset(): void { + self::$innerElementContractCache = null; self::$refPropertyCache = []; self::$propertyMutationPlanCache = []; self::$substitutedElementContractCache = []; @@ -223,6 +238,95 @@ public static function checkProperty( return $value; } + if ( + \count($chain) === 2 + && $chain[0][0] === 'dim' + && $chain[1][0] === 'dim' + && RuntimeTypeChecker::$arrayValidationHybrid + && \is_object($objectOrClass) + ) { + $propPlan = (isset(self::$propertyMutationPlanCache[$className]) && \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) + ? self::$propertyMutationPlanCache[$className][$propName] + : self::buildPropertyMutationPlan($className, $propName); + + if ($propPlan === null) { + return $value; + } + + if (! $propPlan['isMagicOrMissing'] && $propPlan['isNativeNonNullArray']) { + $outerContract = self::resolveElementContractFromPlan($objectOrClass, $className, $propName, $propPlan); + if ($outerContract !== null && $outerContract['valueType'] !== null && (! $outerContract['isList'] || $chain[0][1] === null)) { + $outerValType = $outerContract['valueType']; + self::$innerElementContractCache ??= new WeakMap(); + $innerContract = self::$innerElementContractCache[$outerValType] + ??= (self::buildElementContract($outerValType) ?? false); + + if ($innerContract !== false && (! $innerContract['isList'] || $chain[1][1] === null)) { + $outerKey = $chain[0][1]; + $outerKeyOk = true; + if (! $outerContract['isList'] && $outerKey !== null && $outerContract['keyOp'] !== self::OP_NONE) { + $outerKeyOk = match ($outerContract['keyOp']) { + self::OP_STRING => \is_string($outerKey), + self::OP_INT => \is_int($outerKey), + self::OP_ARRAY_KEY => \is_int($outerKey) || \is_string($outerKey), + self::OP_NON_EMPTY_STRING => \is_string($outerKey) && $outerKey !== '', + self::OP_POSITIVE_INT => \is_int($outerKey) && $outerKey > 0, + default => $outerContract['keyType'] === null + || ($registry ??= RuntimeTypeChecker::getRegistry())->validate($outerKey, $outerContract['keyType'], "Property {$className}::\${$propName} key") === null, + }; + } + + if ($outerKeyOk) { + $innerKey = $chain[1][1]; + $innerKeyOk = true; + if (! $innerContract['isList'] && $innerKey !== null && $innerContract['keyOp'] !== self::OP_NONE) { + $innerKeyOk = match ($innerContract['keyOp']) { + self::OP_STRING => \is_string($innerKey), + self::OP_INT => \is_int($innerKey), + self::OP_ARRAY_KEY => \is_int($innerKey) || \is_string($innerKey), + default => false, + }; + } + + $innerValOk = true; + if ($innerKeyOk && $innerContract['valOp'] !== self::OP_NONE) { + $ivExtra = $innerContract['valExtra']; + $innerValOk = match ($innerContract['valOp']) { + self::OP_STRING => \is_string($value), + self::OP_INT => \is_int($value), + self::OP_BOOL => \is_bool($value), + self::OP_FLOAT => \is_float($value) || \is_int($value), + self::OP_POSITIVE_INT => \is_int($value) && $value > 0, + self::OP_NON_EMPTY_STRING => \is_string($value) && $value !== '', + self::OP_ARRAY => \is_array($value), + self::OP_OBJECT => \is_object($value), + self::OP_CLASS => \is_object($value) && \is_string($ivExtra) && ($value instanceof $ivExtra), + default => false, + }; + } + + if ($innerKeyOk && $innerValOk) { + return $value; + } + + $innerErr = self::validatePropertyElementMutationWithContract( + $className, + $propName, + $innerKey, + $value, + $innerContract, + $registry + ); + + if ($innerErr === null) { + return $value; + } + } + } + } + } + } + if (\count($chain) === 1 && $chain[0][0] === 'dim') { $propPlan = (isset(self::$propertyMutationPlanCache[$className]) && \array_key_exists($propName, self::$propertyMutationPlanCache[$className])) ? self::$propertyMutationPlanCache[$className][$propName] @@ -332,6 +436,19 @@ public static function checkProperty( if ($keyOk && $valOk) { return $value; } + + $directErr = self::validatePropertyElementMutationWithContract( + $className, + $propName, + $key, + $value, + $contract, + $registry + ); + + if ($directErr === null) { + return $value; + } } } } diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 3741d2a2..5d4afd6e 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -25,6 +25,7 @@ use TypePHP\Internal\Generics\TemplateSubstitutor; use TypePHP\Internal\Resolver\HierarchyResolver; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\StubManager; @@ -165,11 +166,24 @@ final class ParamChecker */ private static array $substitutedParamCache = []; + private static ?IdentifierTypeNode $arrayKeyNode = null; + + private static ?UnionTypeNode $intOrStringUnionNode = null; + + /** + * Bitmask of which pre-inference passes a function's parameter signature actually needs: + * 1 = closures, 2 = arrays/iterables, 4 = shapes, 8 = generic objects. + * + * @var array + */ + private static array $preInferMaskCache = []; + /** * Resets internal caches. Useful for test isolation. */ public static function reset(): void { + self::$preInferMaskCache = []; self::$substitutedParamCache = []; self::$effectiveFunctionCache = []; self::$noParamContractCache = []; @@ -283,20 +297,32 @@ public static function checkParams( ); } - self::prepareGenericBindings($effectiveFunction, $methodTemplates, $thisObj, $classTemplates, $thisOrClass); + if ($thisObj === null && $classTemplates === []) { + if ($hasMethodTemplates) { + TemplateManager::pushCallFrame($effectiveFunction, null); + } + } else { + self::prepareGenericBindings($effectiveFunction, $methodTemplates, $thisObj, $classTemplates, $thisOrClass); + } /** @var array $allTemplates */ - $allTemplates = [...$classTemplates, ...$methodTemplates]; + $allTemplates = $classTemplates === [] + ? $methodTemplates + : ($methodTemplates === [] ? $classTemplates : [...$classTemplates, ...$methodTemplates]); - if (\count($allTemplates) > 0 && $paramsUseGenerics && ($contract['paramsNeedPreInference'] ?? true)) { - self::preInferGenericTemplates($contract['types'], $vars, $effectiveFunction, $thisObj, $allTemplates, $classTemplates); + $selfVerifiedParams = []; + + if ($allTemplates !== [] && $paramsUseGenerics && ($contract['paramsNeedPreInference'] ?? true)) { + self::preInferGenericTemplates($contract['types'], $vars, $effectiveFunction, $thisObj, $allTemplates, $classTemplates, $selfVerifiedParams); } $boundTemplates = []; - if (\count($allTemplates) > 0) { - $boundTemplates = ($thisObj !== null && \count($classTemplates) === 0) - ? (TemplateManager::getTopCallFrame($effectiveFunction) ?? []) - : TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates); + if ($allTemplates !== []) { + $boundTemplates = ($thisObj !== null && ! $hasMethodTemplates) + ? TemplateManager::getInstanceBindingsFast($thisObj) + : ($classTemplates === [] + ? (TemplateManager::$topCallFrame[$effectiveFunction] ?? []) + : TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates)); } $declaredTemplates = $allTemplates; @@ -318,7 +344,8 @@ public static function checkParams( $sensitiveParams, $hasMethodTemplates, $functionKind === self::KIND_CONSTRUCT, - $contract['hasCrossReferencedBounds'] ?? true + $contract['hasCrossReferencedBounds'] ?? true, + $selfVerifiedParams ); } @@ -534,6 +561,7 @@ private static function resolveBaseTypes( * @param array $declaredTemplates * @param array $classTemplates * @param array $sensitiveParams + * @param array $selfVerifiedParams */ private static function validateAllParameters( array $contractTypes, @@ -551,7 +579,8 @@ private static function validateAllParameters( array $sensitiveParams = [], bool $hasMethodTemplates = false, bool $isConstructor = false, - bool $hasCrossReferencedBounds = true + bool $hasCrossReferencedBounds = true, + array $selfVerifiedParams = [] ): ?ErrorMessage { $templateCount = \count($allTemplates); $hasClassTemplates = \count($classTemplates) > 0; @@ -562,6 +591,10 @@ private static function validateAllParameters( continue; } + if (isset($selfVerifiedParams[$paramName])) { + continue; + } + if ($isFirstParam) { $currentBoundTemplates = $boundTemplates; $isFirstParam = false; @@ -569,7 +602,7 @@ private static function validateAllParameters( if ($thisObj !== null && ! $hasMethodTemplates && ! $isConstructor) { $currentBoundTemplates = TemplateManager::getInstanceBindingsFast($thisObj); } elseif ($thisObj !== null && ! $hasClassTemplates) { - $currentBoundTemplates = TemplateManager::getTopCallFrame($effectiveFunction) ?? []; + $currentBoundTemplates = TemplateManager::$topCallFrame[$effectiveFunction] ?? []; } else { $currentBoundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates); } @@ -723,6 +756,7 @@ private static function handleMagicCall( * @param array $vars * @param array $templates * @param array $classTemplates + * @param array $selfVerifiedParams */ private static function preInferGenericTemplates( array $types, @@ -730,9 +764,16 @@ private static function preInferGenericTemplates( string $effectiveFunction, ?object $thisObj, array $templates, - array $classTemplates = [] + array $classTemplates = [], + array &$selfVerifiedParams = [] ): void { - if (self::callableNodesFor($effectiveFunction, $types) !== []) { + if ($types === []) { + return; + } + + $mask = self::$preInferMaskCache[$effectiveFunction] ??= self::computePreInferMask($types); + + if (($mask & 1) !== 0) { foreach ($vars as $v) { if ($v instanceof \Closure) { self::inferTemplatesFromClosures($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); @@ -742,13 +783,89 @@ private static function preInferGenericTemplates( } } - if (\count($types) > 0) { - self::inferTemplatesFromArrays($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); + if (($mask & 2) !== 0) { + self::inferTemplatesFromArrays($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates, $selfVerifiedParams); + } + + if (($mask & 4) !== 0) { self::inferTemplatesFromShapes($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + + if (($mask & 8) !== 0) { self::inferTemplatesFromGenericObjects($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); } } + /** + * @param array $types + */ + private static function computePreInferMask(array $types): int + { + $mask = 0; + + foreach ($types as $tNode) { + $mask |= self::computeTypePreInferMask($tNode); + if ($mask === 15) { + break; + } + } + + return $mask; + } + + private static function computeTypePreInferMask(TypeNode $node): int + { + while ($node instanceof NullableTypeNode) { + $node = $node->type; + } + + if ($node instanceof CallableTypeNode) { + return 1; + } + + if ($node instanceof ArrayShapeNode || $node instanceof ObjectShapeNode) { + return 4; + } + + if ($node instanceof ArrayTypeNode) { + $inner = $node->type; + if ($inner instanceof ArrayShapeNode || $inner instanceof ObjectShapeNode) { + return 2 | 4; + } + + return $inner instanceof IdentifierTypeNode ? 0 : 8; + } + + if ($node instanceof GenericTypeNode) { + $base = strtolower((string) $node->type); + if (isset(self::COLLECTION_TYPES[$base])) { + $m = isset(self::TRAVERSABLE_OBJECT_TYPES[$base]) ? (2 | 8) : 2; + foreach ($node->genericTypes as $gt) { + if ($gt instanceof ArrayShapeNode || $gt instanceof ObjectShapeNode) { + $m |= 4; + } elseif (! ($gt instanceof IdentifierTypeNode)) { + $m |= 8; + } + } + + return $m; + } + + return 8; + } + + if ($node instanceof UnionTypeNode || $node instanceof IntersectionTypeNode) { + $m = 0; + foreach ($node->types as $sub) { + $m |= self::computeTypePreInferMask($sub); + } + + return $m; + } + + return 0; + } + /** * Infers generic template parameters from closure parameter typehints and return types. * @@ -1114,6 +1231,7 @@ private static function extractTypeFromClosureParameter(\ReflectionParameter $cl * @param array $vars * @param array $templates * @param array $classTemplates + * @param array $selfVerifiedParams */ private static function inferTemplatesFromArrays( array $types, @@ -1121,14 +1239,17 @@ private static function inferTemplatesFromArrays( string $effectiveFunction, ?object $thisObj, array $templates, - array $classTemplates = [] + array $classTemplates = [], + array &$selfVerifiedParams = [] ): void { foreach ($types as $paramName => $typeNode) { if (! isset($vars[$paramName]) || ! \is_array($vars[$paramName]) || \count($vars[$paramName]) === 0) { continue; } - self::inferArrayTemplatesFromAllElements($typeNode, $vars[$paramName], $effectiveFunction, $thisObj, $templates, $classTemplates); + if (self::inferArrayTemplatesFromAllElements($typeNode, $vars[$paramName], $effectiveFunction, $thisObj, $templates, $classTemplates, true)) { + $selfVerifiedParams[$paramName] = true; + } } } @@ -1301,6 +1422,7 @@ private static function inferTemplateFromTypeAndValue( /** * Extracts and unifies template parameters across all elements of an array argument. * Uses Beartype O(1) hybrid random sampling on arrays > 128 items when hybrid mode is active. + * Returns true when a top-level array<...>/iterable<...> parameter was fully self-verified during inference. * * @param array $arrVal * @param array $templates @@ -1312,78 +1434,231 @@ private static function inferArrayTemplatesFromAllElements( string $effectiveFunction, ?object $thisObj, array $templates, - array $classTemplates = [] - ): void { + array $classTemplates = [], + bool $canSelfVerify = false + ): bool { while ($typeNode instanceof NullableTypeNode) { $typeNode = $typeNode->type; } if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) { foreach ($typeNode->types as $subType) { - self::inferArrayTemplatesFromAllElements($subType, $arrVal, $effectiveFunction, $thisObj, $templates, $classTemplates); + self::inferArrayTemplatesFromAllElements($subType, $arrVal, $effectiveFunction, $thisObj, $templates, $classTemplates, false); } - return; + return false; } if ($typeNode instanceof ArrayTypeNode && ($typeNode->type instanceof ArrayShapeNode || $typeNode->type instanceof ObjectShapeNode)) { $sampleItems = self::getSampleArraySlice($arrVal); self::inferShapeTemplatesFromArraySamples($typeNode->type, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); - return; + return false; } if ($typeNode instanceof GenericTypeNode) { $baseType = strtolower((string) $typeNode->type); if (! isset(self::ITERABLE_TYPES[$baseType])) { - return; + return false; } - $sampleItems = self::getSampleArraySlice($arrVal); $genericCount = \count($typeNode->genericTypes); + $isPlainArrayOrIterable = $canSelfVerify && ($baseType === 'array' || $baseType === 'iterable'); if ($genericCount === 1 && $typeNode->genericTypes[0] instanceof IdentifierTypeNode) { - self::inferSingleTemplateFromArraySamples($typeNode->genericTypes[0]->name, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); - } elseif ($genericCount === 1 && ($typeNode->genericTypes[0] instanceof ArrayShapeNode || $typeNode->genericTypes[0] instanceof ObjectShapeNode)) { + $tName = $typeNode->genericTypes[0]->name; + if (! isset($templates[$tName])) { + return false; + } + + $targetObj = ($thisObj !== null && isset($classTemplates[$tName]) && ! TemplateManager::isMethodTemplate($effectiveFunction, $tName)) + ? $thisObj + : null; + if (TemplateManager::isBound($effectiveFunction, $targetObj, $tName)) { + return false; + } + + $sampleItems = self::getSampleArraySlice($arrVal); + self::inferSingleTemplateFromArraySamples($tName, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); + + return $isPlainArrayOrIterable && TemplateManager::isBound($effectiveFunction, $targetObj, $tName); + } + + if ($genericCount === 1 && ($typeNode->genericTypes[0] instanceof ArrayShapeNode || $typeNode->genericTypes[0] instanceof ObjectShapeNode)) { + $sampleItems = self::getSampleArraySlice($arrVal); self::inferShapeTemplatesFromArraySamples($typeNode->genericTypes[0], $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); - } elseif ($genericCount >= 2) { - $keyTName = $typeNode->genericTypes[0] instanceof IdentifierTypeNode ? $typeNode->genericTypes[0]->name : null; - $valTypeNode = $typeNode->genericTypes[1]; - $valTName = $valTypeNode instanceof IdentifierTypeNode ? $valTypeNode->name : null; - - $inferredKeyType = null; - $inferredValType = null; - - foreach ($sampleItems as $key => $item) { - if ($keyTName !== null) { - $keyType = TemplateManager::inferTypeFromValue($key); - if ($inferredKeyType === null) { - $inferredKeyType = $keyType; - } elseif ($keyType !== $inferredKeyType) { - $inferredKeyType = self::unifyTypes($inferredKeyType, $keyType); + + return false; + } + + if ($genericCount >= 2) { + $keyTypeNode = $typeNode->genericTypes[0]; + $keyTName = null; + $keyTargetObj = null; + $keyIsUnconstrained = false; + + if ($keyTypeNode instanceof IdentifierTypeNode) { + $candidateKey = $keyTypeNode->name; + if (isset($templates[$candidateKey])) { + $keyTargetObj = ($thisObj !== null && isset($classTemplates[$candidateKey]) && ! TemplateManager::isMethodTemplate($effectiveFunction, $candidateKey)) + ? $thisObj + : null; + if (! TemplateManager::isBound($effectiveFunction, $keyTargetObj, $candidateKey)) { + $keyTName = $candidateKey; } + } elseif (\in_array(strtolower($candidateKey), ['array-key', 'mixed'], true)) { + $keyIsUnconstrained = true; } - if ($valTName !== null) { - $valType = TemplateManager::inferTypeFromValue($item); - if ($inferredValType === null) { - $inferredValType = $valType; - } elseif ($valType !== $inferredValType) { - $inferredValType = self::unifyTypes($inferredValType, $valType); + } + + $valTypeNode = $typeNode->genericTypes[1]; + $valTName = null; + $valTargetObj = null; + if ($valTypeNode instanceof IdentifierTypeNode) { + $candidateVal = $valTypeNode->name; + if (isset($templates[$candidateVal])) { + $valTargetObj = ($thisObj !== null && isset($classTemplates[$candidateVal]) && ! TemplateManager::isMethodTemplate($effectiveFunction, $candidateVal)) + ? $thisObj + : null; + if (! TemplateManager::isBound($effectiveFunction, $valTargetObj, $candidateVal)) { + $valTName = $candidateVal; } } } - if ($keyTName !== null && $inferredKeyType !== null) { - self::bindTemplateIfUnbound($keyTName, $inferredKeyType, $effectiveFunction, $thisObj, $templates, $classTemplates); + $valIsShape = ($valTypeNode instanceof ArrayShapeNode || $valTypeNode instanceof ObjectShapeNode); + if ($keyTName === null && $valTName === null && ! $valIsShape) { + return false; } - if ($valTName !== null && $inferredValType !== null) { - self::bindTemplateIfUnbound($valTName, $inferredValType, $effectiveFunction, $thisObj, $templates, $classTemplates); + + $sampleItems = self::getSampleArraySlice($arrVal); + $keyMask = 0; + $valMask = 0; + /** @var array $valTypes */ + $valTypes = []; + $keyBoundOk = false; + $valBoundOk = false; + + if ($keyTName !== null || $valTName !== null) { + foreach ($sampleItems as $key => $item) { + if ($keyTName !== null) { + $keyMask |= \is_int($key) ? 1 : 2; + } + if ($valTName !== null) { + if (\is_string($item)) { + $valMask |= 2; + } elseif (\is_int($item)) { + $valMask |= 1; + } elseif (\is_bool($item)) { + $valMask |= 4; + } elseif (\is_float($item)) { + $valMask |= 8; + } elseif ($item === null) { + $valMask |= 16; + } elseif (\is_object($item)) { + if (TemplateManager::$instanceTemplateBindings !== null && isset(TemplateManager::$instanceTemplateBindings[$item])) { + $objType = TemplateManager::inferTypeFromValue($item); + $valTypes[(string) $objType] = $objType; + } else { + $cls = $item::class; + if (! isset($valTypes[$cls])) { + $valTypes[$cls] = TemplateManager::$classNodeCache[$cls] ??= new IdentifierTypeNode($cls); + } + } + } else { + $itemType = TemplateManager::inferTypeFromValue($item); + $valTypes[(string) $itemType] = $itemType; + } + } + } + + if ($keyTName !== null && $keyMask !== 0) { + $keyTag = $templates[$keyTName]; + if ($keyMask === 1) { + $inferredKeyType = TemplateManager::$intNode ??= new IdentifierTypeNode('int'); + } elseif ($keyMask === 2) { + $inferredKeyType = TemplateManager::$stringNode ??= new IdentifierTypeNode('string'); + } elseif ($keyTag->bound === null || ($keyTag->bound instanceof IdentifierTypeNode && strtolower($keyTag->bound->name) === 'array-key')) { + $inferredKeyType = self::$arrayKeyNode ??= new IdentifierTypeNode('array-key'); + } else { + $inferredKeyType = self::$intOrStringUnionNode ??= new UnionTypeNode([ + TemplateManager::$intNode ??= new IdentifierTypeNode('int'), + TemplateManager::$stringNode ??= new IdentifierTypeNode('string'), + ]); + } + + $boundOk = ($keyTag->bound === null) + || ($keyTag->bound instanceof IdentifierTypeNode && strtolower($keyTag->bound->name) === 'array-key') + || self::doesInferredTypeSatisfyBound($keyTName, $inferredKeyType, $effectiveFunction, $thisObj, $templates); + + if ($boundOk) { + TemplateManager::bindTemplate($effectiveFunction, $keyTargetObj, $keyTName, $inferredKeyType); + $keyBoundOk = true; + } + } + + if ($valTName !== null && ($valMask !== 0 || $valTypes !== []) && (! $keyBoundOk || $valTName !== $keyTName)) { + $inferredValType = self::buildInferredValueTypeNode($valMask, $valTypes); + if (self::doesInferredTypeSatisfyBound($valTName, $inferredValType, $effectiveFunction, $thisObj, $templates)) { + TemplateManager::bindTemplate($effectiveFunction, $valTargetObj, $valTName, $inferredValType); + $valBoundOk = true; + } + } } + if ($valTypeNode instanceof ArrayShapeNode || $valTypeNode instanceof ObjectShapeNode) { self::inferShapeTemplatesFromArraySamples($valTypeNode, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); } + + return $isPlainArrayOrIterable + && $valBoundOk + && ($keyBoundOk || $keyIsUnconstrained) + && $keyTName !== $valTName; } } + + return false; + } + + /** + * @param array $valTypes + */ + private static function buildInferredValueTypeNode(int $valMask, array $valTypes): TypeNode + { + if ($valTypes === []) { + if ($valMask === 2) { + return TemplateManager::$stringNode ??= new IdentifierTypeNode('string'); + } + if ($valMask === 1) { + return TemplateManager::$intNode ??= new IdentifierTypeNode('int'); + } + if ($valMask === 4) { + return TemplateManager::$boolNode ??= new IdentifierTypeNode('bool'); + } + if ($valMask === 8) { + return TemplateManager::$floatNode ??= new IdentifierTypeNode('float'); + } + } + + if (($valMask & 1) !== 0 && ! isset($valTypes['int'])) { + $valTypes['int'] = TemplateManager::$intNode ??= new IdentifierTypeNode('int'); + } + if (($valMask & 2) !== 0 && ! isset($valTypes['string'])) { + $valTypes['string'] = TemplateManager::$stringNode ??= new IdentifierTypeNode('string'); + } + if (($valMask & 4) !== 0 && ! isset($valTypes['bool'])) { + $valTypes['bool'] = TemplateManager::$boolNode ??= new IdentifierTypeNode('bool'); + } + if (($valMask & 8) !== 0 && ! isset($valTypes['float'])) { + $valTypes['float'] = TemplateManager::$floatNode ??= new IdentifierTypeNode('float'); + } + if (($valMask & 16) !== 0 && ! isset($valTypes['null'])) { + $valTypes['null'] = new IdentifierTypeNode('null'); + } + + $values = array_values($valTypes); + + return \count($values) === 1 ? $values[0] : new UnionTypeNode($values); } /** @@ -1543,7 +1818,9 @@ private static function inferSingleTemplateFromArraySamples( array $templates, array $classTemplates = [] ): void { - $inferredType = null; + $valMask = 0; + /** @var array $valTypes */ + $valTypes = []; $hasEmptyArray = false; foreach ($sampleItems as $item) { @@ -1552,10 +1829,37 @@ private static function inferSingleTemplateFromArraySamples( continue; } - $itemType = TemplateManager::inferTypeFromValue($item); - $inferredType = ($inferredType === null) ? $itemType : self::unifyTypes($inferredType, $itemType); + + if (\is_string($item)) { + $valMask |= 2; + } elseif (\is_int($item)) { + $valMask |= 1; + } elseif (\is_bool($item)) { + $valMask |= 4; + } elseif (\is_float($item)) { + $valMask |= 8; + } elseif ($item === null) { + $valMask |= 16; + } elseif (\is_object($item)) { + if (TemplateManager::$instanceTemplateBindings !== null && isset(TemplateManager::$instanceTemplateBindings[$item])) { + $objType = TemplateManager::inferTypeFromValue($item); + $valTypes[(string) $objType] = $objType; + } else { + $cls = $item::class; + if (! isset($valTypes[$cls])) { + $valTypes[$cls] = TemplateManager::$classNodeCache[$cls] ??= new IdentifierTypeNode($cls); + } + } + } else { + $itemType = TemplateManager::inferTypeFromValue($item); + $valTypes[(string) $itemType] = $itemType; + } } + $inferredType = ($valMask !== 0 || $valTypes !== []) + ? self::buildInferredValueTypeNode($valMask, $valTypes) + : null; + if ($hasEmptyArray) { $emptyListNode = TemplateManager::inferTypeFromValue([]); if ($inferredType === null) { @@ -1605,7 +1909,7 @@ private static function isCollectionTypeNode(TypeNode $node): bool private static function getSampleArraySlice(array $arrVal): array { $count = \count($arrVal); - if ($count <= Config::HYBRID_SAMPLE_THRESHOLD || ! Config::isArrayValidationHybrid()) { + if ($count <= Config::HYBRID_SAMPLE_THRESHOLD || ! RuntimeTypeChecker::$arrayValidationHybrid) { return $arrVal; } @@ -1639,14 +1943,21 @@ private static function bindTemplateIfUnbound( array $templates, array $classTemplates = [] ): void { - if ($classTemplates === []) { + if (! isset($templates[$templateName])) { + return; + } + + if ($classTemplates === [] && $thisObj !== null && str_contains($effectiveFunction, '::')) { $contract = DocblockParser::parse($effectiveFunction); $classTemplates = $contract['classTemplates'] ?? []; } - $isClassLevelTemplate = ! TemplateManager::isMethodTemplate($effectiveFunction, $templateName) && isset($classTemplates[$templateName]); + + $isClassLevelTemplate = $thisObj !== null + && isset($classTemplates[$templateName]) + && ! TemplateManager::isMethodTemplate($effectiveFunction, $templateName); $targetObj = $isClassLevelTemplate ? $thisObj : null; - if (isset($templates[$templateName]) && ! TemplateManager::isBound($effectiveFunction, $targetObj, $templateName)) { + if (! TemplateManager::isBound($effectiveFunction, $targetObj, $templateName)) { if (self::doesInferredTypeSatisfyBound($templateName, $inferredType, $effectiveFunction, $thisObj, $templates)) { TemplateManager::bindTemplate($effectiveFunction, $targetObj, $templateName, $inferredType); } @@ -1718,8 +2029,19 @@ private static function inferGenericObjectNode( } if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) { + $isObj = \is_object($value); foreach ($typeNode->types as $subType) { - self::inferGenericObjectNode($subType, $value, $effectiveFunction, $thisObj, $templates, $classTemplates); + if ($subType instanceof GenericTypeNode) { + if ($isObj || isset(self::COLLECTION_TYPES[strtolower((string) $subType->type)])) { + self::inferGenericObjectNode($subType, $value, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + } elseif ($subType instanceof ArrayTypeNode) { + if (! $isObj && ! ($subType->type instanceof IdentifierTypeNode)) { + self::inferGenericObjectNode($subType, $value, $effectiveFunction, $thisObj, $templates, $classTemplates); + } + } elseif ($subType instanceof NullableTypeNode || $subType instanceof UnionTypeNode || $subType instanceof IntersectionTypeNode) { + self::inferGenericObjectNode($subType, $value, $effectiveFunction, $thisObj, $templates, $classTemplates); + } } return; @@ -1824,7 +2146,7 @@ private static function inferGenericObjectNode( } } - if ($innerType !== null) { + if ($innerType !== null && ! ($innerType instanceof IdentifierTypeNode)) { foreach ($value as $item) { if (\is_object($item)) { self::inferGenericObjectNode($innerType, $item, $effectiveFunction, $thisObj, $templates, $classTemplates); @@ -1904,7 +2226,7 @@ private static function inferTemplatesFromIterableObject( $inferredKey = SpecialTypeResolver::resolve($inferredKey, $genContext, $genThis); } if (ConditionalChecker::containsConditional($inferredKey)) { - $inferredKey = ConditionalChecker::resolve($inferredKey, [], $boundOnGenThis, \TypePHP\Internal\RuntimeTypeChecker::getRegistry(), $genFunctionName); + $inferredKey = ConditionalChecker::resolve($inferredKey, [], $boundOnGenThis, RuntimeTypeChecker::getRegistry(), $genFunctionName); if ($genContext !== null) { $inferredKey = SpecialTypeResolver::resolve($inferredKey, $genContext, $genThis); } @@ -1920,7 +2242,7 @@ private static function inferTemplatesFromIterableObject( $inferredVal = SpecialTypeResolver::resolve($inferredVal, $genContext, $genThis); } if (ConditionalChecker::containsConditional($inferredVal)) { - $inferredVal = ConditionalChecker::resolve($inferredVal, [], $boundOnGenThis, \TypePHP\Internal\RuntimeTypeChecker::getRegistry(), $genFunctionName); + $inferredVal = ConditionalChecker::resolve($inferredVal, [], $boundOnGenThis, RuntimeTypeChecker::getRegistry(), $genFunctionName); if ($genContext !== null) { $inferredVal = SpecialTypeResolver::resolve($inferredVal, $genContext, $genThis); } diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index 52ba80eb..a70a6dd0 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -64,11 +64,19 @@ final class ReturnChecker */ public static array $substitutedReturnCache = []; + /** + * Cache for substituted conditional return branches: [$cacheFunc][$branchStr][$sig] => TypeNode. + * + * @var array>> + */ + public static array $substitutedConditionalReturnCache = []; + /** * Resets internal caches. Useful for test isolation. */ public static function reset(): void { + self::$substitutedConditionalReturnCache = []; self::$noReturnContractCache = []; self::$resolvedStaticReturnCache = []; self::$unboundReturnCache = []; @@ -398,7 +406,7 @@ private static function evaluateReturn( if ($thisObj !== null && ! $hasMethodTemplates) { $boundTemplates = $hasClassTemplates ? TemplateManager::getInstanceBindingsFast($thisObj) : []; } elseif ($thisObj !== null && ! $hasClassTemplates) { - $boundTemplates = TemplateManager::getTopCallFrame($function) ?? []; + $boundTemplates = TemplateManager::$topCallFrame[$function] ?? []; } else { $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); } @@ -410,7 +418,7 @@ private static function evaluateReturn( $cacheFunc = null; $boundCount = \count($boundTemplates); - if ($boundCount <= 5 && ! $hasConditionals && ($thisObj !== null || ! $isDynamicReturn)) { + if ($boundCount <= 5 && ($thisObj !== null || ! $isDynamicReturn)) { $cacheFunc = ($isDynamicReturn && $thisObj !== null) ? ($function . '@' . $thisObj::class) : $function; if ($boundCount === 0) { @@ -428,7 +436,7 @@ private static function evaluateReturn( if (str_contains($sig, 'static') || str_contains($sig, '$this')) { $sig = null; - } elseif (isset(self::$substitutedReturnCache[$cacheFunc][$sig])) { + } elseif (! $hasConditionals && isset(self::$substitutedReturnCache[$cacheFunc][$sig])) { $resolvedType = self::$substitutedReturnCache[$cacheFunc][$sig]; } } @@ -442,29 +450,45 @@ private static function evaluateReturn( $resolvedType = $aliases[$resolvedType->name]; } - if (ConditionalChecker::containsConditional($resolvedType)) { + if ($hasConditionals || (! ($resolvedType instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($resolvedType))) { $resolvedType = ConditionalChecker::resolve($resolvedType, $vars, $boundTemplates, $registry, $function); } - if ($boundCount === 0 && \count($templates) > 0 && ! $hasConditionals && $thisObj === null) { - $resolvedType = self::$unboundReturnCache[$function] ??= SpecialTypeResolver::resolve( - TemplateSubstitutor::substitute($returnTypeNode, [], $templates), - $function, - null - ); - } elseif ($boundCount > 0 || \count($templates) > 0) { - $subType = TemplateSubstitutor::substitute($resolvedType, $boundTemplates, $templates); - $resolvedType = ($isDynamicReturn || $subType !== $resolvedType) - ? SpecialTypeResolver::resolve($subType, $function, $thisObj) - : $subType; + $condBranchKey = null; + $condCacheHit = false; + if ($hasConditionals && $sig !== null && $cacheFunc !== null) { + $condBranchKey = (string) $resolvedType; + if (isset(self::$substitutedConditionalReturnCache[$cacheFunc][$condBranchKey][$sig])) { + $resolvedType = self::$substitutedConditionalReturnCache[$cacheFunc][$condBranchKey][$sig]; + $condCacheHit = true; + } } - if (ConditionalChecker::containsConditional($resolvedType)) { - $resolvedType = ConditionalChecker::resolve($resolvedType, $vars, $boundTemplates, $registry, $function); - } + if (! $condCacheHit) { + if ($boundCount === 0 && \count($templates) > 0 && ! $hasConditionals && $thisObj === null) { + $resolvedType = self::$unboundReturnCache[$function] ??= SpecialTypeResolver::resolve( + TemplateSubstitutor::substitute($returnTypeNode, [], $templates), + $function, + null + ); + } elseif ($boundCount > 0 || \count($templates) > 0) { + $subType = TemplateSubstitutor::substitute($resolvedType, $boundTemplates, $templates); + $resolvedType = $isDynamicReturn + ? SpecialTypeResolver::resolve($subType, $function, $thisObj) + : $subType; + } - if ($sig !== null && $cacheFunc !== null) { - self::$substitutedReturnCache[$cacheFunc][$sig] = $resolvedType; + if (! ($resolvedType instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($resolvedType)) { + $resolvedType = ConditionalChecker::resolve($resolvedType, $vars, $boundTemplates, $registry, $function); + } + + if ($sig !== null && $cacheFunc !== null) { + if ($hasConditionals && $condBranchKey !== null) { + self::$substitutedConditionalReturnCache[$cacheFunc][$condBranchKey][$sig] = $resolvedType; + } elseif (! $hasConditionals) { + self::$substitutedReturnCache[$cacheFunc][$sig] = $resolvedType; + } + } } } diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index 25784c22..9af078e9 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -58,6 +58,10 @@ * allParamsUnconstrained: bool, * returnUnconstrained: bool, * returnHasConditional?: bool, + * returnAllowsNull?: bool, + * paramsAreSimple?: bool, + * hasCrossReferencedBounds?: bool, + * paramsNeedPreInference?: bool, * isSimple: bool * } * @@ -310,6 +314,7 @@ private static function isUnconstrainedType(TypeNode $typeNode): bool * allParamsUnconstrained: bool, * returnUnconstrained: bool, * returnHasConditional: bool, + * returnAllowsNull: bool, * isSimple: bool, * paramsAreSimple: bool, * hasCrossReferencedBounds: bool, @@ -324,7 +329,8 @@ private static function computeContractFlags( array $aliases, array $methodTemplates, bool $paramsAreDynamic = false, - array $allTemplates = [] + array $allTemplates = [], + bool $returnIsThis = false ): array { $constrainedTypes = []; $paramConditionals = []; @@ -344,7 +350,14 @@ private static function computeContractFlags( $inner = $inner->type; } if (! ($inner instanceof IdentifierTypeNode)) { - $paramsNeedPreInference = true; + if ($inner instanceof GenericTypeNode) { + $base = strtolower((string) $inner->type); + if (! \in_array($base, ['class-string', 'int', 'integer', 'int-mask', 'int-mask-of', 'key-of', 'value-of'], true)) { + $paramsNeedPreInference = true; + } + } else { + $paramsNeedPreInference = true; + } } } } @@ -360,6 +373,11 @@ private static function computeContractFlags( $returnHasConditional = ConditionalChecker::containsConditional($returnType); } + $returnAllowsNull = $returnType !== null + && ! $returnIsThis + && ! $returnHasConditional + && self::typeContainsNull($returnType); + $paramsAreSimple = ! $paramsUseGenerics && ! $paramsAreDynamic && \count($aliases) === 0 @@ -384,6 +402,7 @@ private static function computeContractFlags( 'allParamsUnconstrained' => $allParamsUnconstrained, 'returnUnconstrained' => $returnUnconstrained, 'returnHasConditional' => $returnHasConditional, + 'returnAllowsNull' => $returnAllowsNull, 'isSimple' => $isSimple, 'paramsAreSimple' => $paramsAreSimple, 'hasCrossReferencedBounds' => $hasCrossReferencedBounds, @@ -1104,7 +1123,9 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t $returnUsesGenerics, $aliases, $methodTemplates, - $paramsAreDynamic + $paramsAreDynamic, + $allTemplates, + $returnIsThis ); return [ @@ -1132,6 +1153,10 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t 'allParamsUnconstrained' => $flags['allParamsUnconstrained'], 'returnUnconstrained' => $flags['returnUnconstrained'], 'returnHasConditional' => $flags['returnHasConditional'], + 'returnAllowsNull' => $flags['returnAllowsNull'], + 'paramsAreSimple' => $flags['paramsAreSimple'], + 'hasCrossReferencedBounds' => $flags['hasCrossReferencedBounds'], + 'paramsNeedPreInference' => $flags['paramsNeedPreInference'], 'isSimple' => $flags['isSimple'], ]; } @@ -1193,16 +1218,26 @@ private static function parseFunction(\ReflectionFunction $ref): array 'allParamsUnconstrained' => true, 'returnUnconstrained' => false, 'returnHasConditional' => false, + 'returnAllowsNull' => false, + 'paramsAreSimple' => true, + 'hasCrossReferencedBounds' => false, + 'paramsNeedPreInference' => false, 'isSimple' => true, ]; } $phpDocNode = DocblockExtractor::parseDocString($doc); + DocblockExtractor::extractAliases($phpDocNode, $aliases, $ref); + foreach (DocblockExtractor::extractTemplates($phpDocNode) as $name => $tag) { + if ($tag->bound !== null || $tag->default !== null) { + $bound = $tag->bound !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->bound, $aliases), $ref) : null; + $default = $tag->default !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->default, $aliases), $ref) : null; + $tag = new TemplateTagValueNode($tag->name, $bound, $tag->description, $default); + } $templates[$name] = $tag; } - DocblockExtractor::extractAliases($phpDocNode, $aliases, $ref); $paramIndex = 0; foreach (DocblockExtractor::getParamTags($phpDocNode) as $paramName => $paramTag) { @@ -1297,7 +1332,9 @@ private static function parseFunction(\ReflectionFunction $ref): array $returnUsesMethodTemplates, $aliases, $templates, - false + false, + $templates, + $returnIsThis ); return [ @@ -1325,6 +1362,10 @@ private static function parseFunction(\ReflectionFunction $ref): array 'allParamsUnconstrained' => $flags['allParamsUnconstrained'], 'returnUnconstrained' => $flags['returnUnconstrained'], 'returnHasConditional' => $flags['returnHasConditional'], + 'returnAllowsNull' => $flags['returnAllowsNull'], + 'paramsAreSimple' => $flags['paramsAreSimple'], + 'hasCrossReferencedBounds' => $flags['hasCrossReferencedBounds'], + 'paramsNeedPreInference' => $flags['paramsNeedPreInference'], 'isSimple' => $flags['isSimple'], ]; } @@ -1483,12 +1524,18 @@ private static function parseMethodHierarchyDocs( $phpDocNode = DocblockExtractor::parseDocString($doc); + DocblockExtractor::extractAliases($phpDocNode, $aliases, $hierRef); + foreach (DocblockExtractor::extractTemplates($phpDocNode) as $name => $tag) { if (! isset($templates[$name])) { + if ($tag->bound !== null || $tag->default !== null) { + $bound = $tag->bound !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->bound, $aliases), $hierRef) : null; + $default = $tag->default !== null ? SpecialTypeResolver::resolve(self::substituteAliases($tag->default, $aliases), $hierRef) : null; + $tag = new TemplateTagValueNode($tag->name, $bound, $tag->description, $default); + } $templates[$name] = $tag; } } - DocblockExtractor::extractAliases($phpDocNode, $aliases, $hierRef); $paramTags = DocblockExtractor::getParamTags($phpDocNode); diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index be43e32b..654e2ab5 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -58,13 +58,6 @@ final class TemplateManager */ private static array $callStackBindings = []; - /** - * Sequential execution order of active function call frames on the stack. - * - * @var list - */ - private static array $activeCallOrder = []; - /** * Cache for resolved hierarchy templates and variances per class name. * @@ -616,11 +609,34 @@ final class TemplateManager */ private static ?WeakMap $verifiedShallowRefinements = null; + /** + * Direct O(1) active top call frame per function (eliminates nested stack access on non-recursive calls). + * + * @var array> + */ + public static array $topCallFrame = []; + + /** + * Sequential execution order of active function call frames on the stack. + * + * @var list + */ + public static array $activeCallOrder = []; + + /** + * Direct O(1) active $this object per function. + * + * @var array + */ + public static array $topCallThis = []; + /** * Resets all static generic template bindings, call stack frames, and method template caches. */ public static function reset(): void { + self::$topCallFrame = []; + self::$topCallThis = []; self::$propagatedBindingsCache = null; self::$refClassCache = []; self::$instanceTemplateBindings = null; @@ -671,6 +687,21 @@ public static function restoreInstanceBindings(object $instance, array $bindings } } + /** + * Pushes a pre-bound single-template call frame onto the stack in O(1). + */ + public static function pushSingleTemplateFrame(string $function, string $templateName, TypeNode $type, ?object $thisObj = null): void + { + if (isset(self::$topCallFrame[$function])) { + self::$callStackBindings[$function][] = self::$topCallFrame[$function]; + self::$callStackThis[$function][] = self::$topCallThis[$function] ?? null; + } + + self::$topCallFrame[$function] = [$templateName => $type]; + self::$topCallThis[$function] = $thisObj; + self::$activeCallOrder[] = $function; + } + /** * Pushes a pending generic instantiation for a constructor. */ @@ -855,8 +886,13 @@ public static function copyInstanceBindings(object $source, object $target): voi */ public static function pushCallFrame(string $function, ?object $thisObj = null): void { - self::$callStackBindings[$function][] = []; - self::$callStackThis[$function][] = $thisObj; + if (isset(self::$topCallFrame[$function])) { + self::$callStackBindings[$function][] = self::$topCallFrame[$function]; + self::$callStackThis[$function][] = self::$topCallThis[$function] ?? null; + } + + self::$topCallFrame[$function] = []; + self::$topCallThis[$function] = $thisObj; self::$activeCallOrder[] = $function; } @@ -866,17 +902,22 @@ public static function pushCallFrame(string $function, ?object $thisObj = null): public static function popCallFrame(string $function): void { if (isset(self::$callStackBindings[$function])) { - array_pop(self::$callStackBindings[$function]); - if (isset(self::$callStackThis[$function])) { - array_pop(self::$callStackThis[$function]); - } + $prev = array_pop(self::$callStackBindings[$function]); + $prevThis = array_pop(self::$callStackThis[$function]); if (self::$callStackBindings[$function] === []) { - unset(self::$callStackBindings[$function], self::$callStackThis[$function], self::$generatorInferredCallFrames[$function]); + unset(self::$callStackBindings[$function], self::$callStackThis[$function]); } + self::$topCallFrame[$function] = $prev ?? []; + self::$topCallThis[$function] = $prevThis; + } else { + unset(self::$topCallFrame[$function], self::$topCallThis[$function], self::$generatorInferredCallFrames[$function]); + } + $count = \count(self::$activeCallOrder); + if ($count > 0 && self::$activeCallOrder[$count - 1] === $function) { + array_pop(self::$activeCallOrder); + } elseif ($count > 1) { self::popActiveCallOrder($function); - } else { - unset(self::$generatorInferredCallFrames[$function]); } } @@ -913,13 +954,7 @@ private static function popActiveCallOrder(string $function): void */ private static function getTopCallThis(string $function): ?object { - if (! isset(self::$callStackThis[$function]) || self::$callStackThis[$function] === []) { - return null; - } - - $top = end(self::$callStackThis[$function]); - - return $top !== false ? $top : null; + return self::$topCallThis[$function] ?? null; } /** @@ -1014,7 +1049,7 @@ public static function getBoundTemplates(string $function, object|string|null $t } } - $topFrame = self::getTopCallFrame($function); + $topFrame = self::$topCallFrame[$function] ?? null; if ($topFrame !== null) { $bindings = $bindings === [] ? $topFrame @@ -1173,8 +1208,7 @@ public static function getMethodTemplates(string $function): array */ public static function isBound(string $function, object|string|null $thisOrClass, string $templateName): bool { - $topFrame = self::getTopCallFrame($function); - if ($topFrame !== null && isset($topFrame[$templateName])) { + if (isset(self::$topCallFrame[$function][$templateName])) { return true; } @@ -1217,9 +1251,8 @@ public static function isBound(string $function, object|string|null $thisOrClass */ public static function getBoundType(string $function, object|string|null $thisOrClass, string $templateName): ?TypeNode { - $topFrame = self::getTopCallFrame($function); - if ($topFrame !== null && isset($topFrame[$templateName])) { - return $topFrame[$templateName]; + if (isset(self::$topCallFrame[$function][$templateName])) { + return self::$topCallFrame[$function][$templateName]; } $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; @@ -1275,12 +1308,13 @@ public static function bindTemplate(string $function, ?object $thisObj, string $ self::$instanceTemplateBindings[$thisObj] = $bindings; } else { - if (! self::hasCallFrame($function)) { - self::$callStackBindings[$function][] = []; + if (! isset(self::$topCallFrame[$function])) { + self::$topCallFrame[$function] = [$templateName => $inferredType]; + self::$topCallThis[$function] = null; self::$activeCallOrder[] = $function; + } else { + self::$topCallFrame[$function][$templateName] = $inferredType; } - $lastIndex = \count(self::$callStackBindings[$function]) - 1; - self::$callStackBindings[$function][$lastIndex][$templateName] = $inferredType; } } @@ -1997,7 +2031,7 @@ private static function widenClonedBindingsFromActiveCall(object $target, array return $bindings; } - $topFrame = self::getTopCallFrame($activeFunction); + $topFrame = self::$topCallFrame[$activeFunction] ?? null; if ($topFrame === null || $topFrame === []) { return $bindings; } @@ -2021,7 +2055,7 @@ private static function widenClonedBindingsFromActiveCall(object $target, array $returnTemplateNames = array_keys(DocblockParser::parseClassTemplates($returnBaseClass)); $targetTemplateNames = array_keys($targetTemplates); - $activeThis = self::getTopCallThis($activeFunction); + $activeThis = self::$topCallThis[$activeFunction] ?? null; $thisBindings = $activeThis !== null ? self::getBoundTemplatesForInstance($activeThis) : []; $combinedBindings = [...$thisBindings, ...$bindings, ...$topFrame]; $changed = false; @@ -3600,7 +3634,7 @@ private static function collectMatchingObjectGenericNodes(object $instance, Type */ private static function hasCallFrame(string $function): bool { - return isset(self::$callStackBindings[$function]); + return isset(self::$topCallFrame[$function]); } /** @@ -3608,13 +3642,7 @@ private static function hasCallFrame(string $function): bool */ public static function getTopCallFrame(string $function): ?array { - if (! isset(self::$callStackBindings[$function]) || self::$callStackBindings[$function] === []) { - return null; - } - - $top = end(self::$callStackBindings[$function]); - - return $top !== false ? $top : null; + return self::$topCallFrame[$function] ?? null; } private static function ensureInstanceInherited(object $instance): void diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 4252605a..e9a645f5 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -28,7 +28,9 @@ use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Reporting\ViolationCollector; use TypePHP\Internal\Resolver\CallerBoundaryResolver; +use TypePHP\Internal\Resolver\HierarchyResolver; use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\IgnoreManager; use TypePHP\Internal\Validator\TypeValidatorRegistry; @@ -78,6 +80,10 @@ final class RuntimeTypeChecker private const PARAM_CHECK_SCALAR = 18; + private const PARAM_CHECK_OBJECT = 19; + + private const PARAM_CHECK_CLASS = 20; + public static bool $isEnabled = true; public static bool $paramsEnabled = true; @@ -105,7 +111,7 @@ final class RuntimeTypeChecker private static array $simpleCtorTemplatePlanCache = []; /** - * @var array + * @var array */ private static array $simpleReturnPlanCache = []; @@ -126,11 +132,56 @@ final class RuntimeTypeChecker */ private static array $genericReturnPlanCache = []; + /** + * @var array}>> + */ + private static array $traitScopePlanCache = []; + + /** + * @var array> + */ + private static array $traitReturnPlanCache = []; + + /** + * @var array + */ + private static array $nullableReturnCache = []; + + /** + * @var array> + */ + private static array $traitNullableReturnCache = []; + + /** + * Compiled fast-path for methods with a single class-string method template (bound null or object) + * and optional simple scalar/bool parameters (e.g. HasAttributes::getAttribute/getAttributes). + * + * @var array}>> + */ + private static array $simpleClassStringTemplatePlanCache = []; + + /** + * @var array + */ + private static array $identitySelfReturnCache = []; + + /** + * @var array> + */ + private static array $traitIdentitySelfReturnCache = []; + /** * Resets runtime caches. */ public static function reset(): void { + self::$identitySelfReturnCache = []; + self::$traitIdentitySelfReturnCache = []; + self::$simpleClassStringTemplatePlanCache = []; + self::$traitScopePlanCache = []; + self::$traitReturnPlanCache = []; + self::$nullableReturnCache = []; + self::$traitNullableReturnCache = []; self::$simpleScopePlanCache = []; self::$simpleCtorTemplatePlanCache = []; self::$simpleReturnPlanCache = []; @@ -303,6 +354,11 @@ public static function checkPropertyMemberAssign( return $value; } + $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); + if ($className !== '' && isset(InlineChecker::$nullPropertyCache[$className][$propName])) { + return $value; + } + if ( self::$arrayValidationHybrid && \is_object($objectOrClass) @@ -461,6 +517,11 @@ public static function checkPropertyDimAssign( return $value; } + $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); + if ($className !== '' && isset(InlineChecker::$nullPropertyCache[$className][$propName])) { + return $value; + } + if ( self::$arrayValidationHybrid && \is_object($objectOrClass) @@ -763,6 +824,67 @@ public static function setupScope(string $function, array $vars, object|string|n } } + $classKey = \is_object($thisOrClass) ? $thisOrClass::class : (\is_string($thisOrClass) ? $thisOrClass : ''); + if (isset(self::$simpleClassStringTemplatePlanCache[$function][$classKey])) { + $csPlan = self::$simpleClassStringTemplatePlanCache[$function][$classKey]; + $pName = $csPlan['paramName']; + if (isset($vars[$pName])) { + $valStr = $vars[$pName]; + if ( + \is_string($valStr) + && (ClassNameValidator::$validClassStringCache[$valStr] + ?? ClassNameValidator::isValidClassString($valStr)) + ) { + $othersOk = true; + foreach ($csPlan['otherParams'] as $op) { + $opName = $op[0]; + if (isset($vars[$opName])) { + $ov = $vars[$opName]; + $ok = match ($op[1]) { + self::PARAM_CHECK_BOOL => \is_bool($ov), + self::PARAM_CHECK_INT => \is_int($ov), + self::PARAM_CHECK_STRING => \is_string($ov), + self::PARAM_CHECK_FLOAT => \is_float($ov) || \is_int($ov), + self::PARAM_CHECK_ARRAY => \is_array($ov), + self::PARAM_CHECK_POSITIVE_INT => \is_int($ov) && $ov > 0, + self::PARAM_CHECK_NON_EMPTY_STRING => \is_string($ov) && $ov !== '', + default => false, + }; + if (! $ok) { + $othersOk = false; + + break; + } + } elseif (\array_key_exists($opName, $vars)) { + $othersOk = false; + + break; + } + } + + if ($othersOk) { + $classNode = TemplateManager::$classNodeCache[$valStr] ??= new IdentifierTypeNode($valStr); + $eff = $csPlan['effective']; + $tName = $csPlan['templateName']; + $thisObjVal = \is_object($thisOrClass) ? $thisOrClass : null; + + if (isset(TemplateManager::$topCallFrame[$eff])) { + TemplateManager::pushSingleTemplateFrame($eff, $tName, $classNode, $thisObjVal); + } else { + TemplateManager::$topCallFrame[$eff] = [$tName => $classNode]; + TemplateManager::$topCallThis[$eff] = $thisObjVal; + TemplateManager::$activeCallOrder[] = $eff; + } + + $cleaner = new ScopeCleaner($eff); + $cleaner->boundTemplates = [$tName => $classNode]; + + return $cleaner; + } + } + } + } + $plan = self::$simpleScopePlanCache[$function] ?? null; if ( @@ -776,8 +898,14 @@ public static function setupScope(string $function, array $vars, object|string|n return self::executeSimpleScopePlan($plan, $vars); } + if (\is_object($thisOrClass) && isset(self::$traitScopePlanCache[$function][$thisOrClass::class])) { + return self::executeSimpleScopePlan(self::$traitScopePlanCache[$function][$thisOrClass::class], $vars); + } + $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + $effectiveFunction = $thisOrClass === null + ? $function + : ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); if ($effectiveFunction !== $function && isset(self::$simpleScopePlanCache[$effectiveFunction])) { $effectivePlan = self::$simpleScopePlanCache[$effectiveFunction]; @@ -869,6 +997,8 @@ public static function setupScope(string $function, array $vars, object|string|n self::$simpleScopePlanCache[$effectiveFunction] = $compiledPlan; if ($function === $effectiveFunction) { self::$simpleScopePlanCache[$function] = $compiledPlan; + } elseif ($thisObj !== null && HierarchyResolver::getTraitAliases($thisObj::class) === []) { + self::$traitScopePlanCache[$function][$thisObj::class] = $compiledPlan; } } @@ -898,6 +1028,30 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } + if ( + ! $isMagicCall + && $functionKind !== ParamChecker::KIND_CONSTRUCT + && \count($contract['templates']) === 1 + && $contract['classTemplates'] === [] + && $contract['aliases'] === [] + && ! $contract['paramsAreDynamic'] + && ($contract['paramConditionals'] ?? []) === [] + && ! ($contract['hasCrossReferencedBounds'] ?? false) + && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) + && ($thisObj === null || HierarchyResolver::getTraitAliases($thisObj::class) === []) + ) { + $csPlan = self::compileSimpleClassStringTemplatePlan( + $effectiveFunction, + $contract['types'], + $contract['templates'], + $contract['sensitiveParams'] + ); + if ($csPlan !== null) { + self::$simpleClassStringTemplatePlanCache[$function][$classKey] = $csPlan; + self::$hasMethodTemplatesCache[$effectiveFunction] = true; + } + } + $err = ParamChecker::checkParams( $function, $vars, @@ -933,7 +1087,7 @@ public static function setupScope(string $function, array $vars, object|string|n if ($hasMethodTemplates) { $cleaner = new ScopeCleaner($effectiveFunction); if ($thisObj !== null && $contract['classTemplates'] === []) { - $cleaner->boundTemplates = TemplateManager::getTopCallFrame($effectiveFunction) ?? []; + $cleaner->boundTemplates = TemplateManager::$topCallFrame[$effectiveFunction] ?? []; } else { $allTemplates = [...$contract['classTemplates'], ...$contract['templates']]; $cleaner->boundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $allTemplates); @@ -945,6 +1099,95 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } + /** + * @param array $types + * @param array $templates + * @param array $sensitiveParams + * + * @return array{effective: string, paramName: string, templateName: string, otherParams: list}|null + */ + private static function compileSimpleClassStringTemplatePlan( + string $effectiveFunction, + array $types, + array $templates, + array $sensitiveParams + ): ?array { + if (\count($templates) !== 1 || $types === []) { + return null; + } + + $tName = (string) array_key_first($templates); + $tTag = $templates[$tName]; + if ($tTag->bound !== null) { + if (! ($tTag->bound instanceof IdentifierTypeNode)) { + return null; + } + $boundLower = strtolower($tTag->bound->name); + if ($boundLower !== 'object' && $boundLower !== 'mixed') { + return null; + } + } + + $classStringParamName = null; + $otherParams = []; + + foreach ($types as $paramName => $typeNode) { + if ( + $typeNode instanceof GenericTypeNode + && strtolower((string) $typeNode->type) === 'class-string' + && \count($typeNode->genericTypes) === 1 + && $typeNode->genericTypes[0] instanceof IdentifierTypeNode + && $typeNode->genericTypes[0]->name === $tName + ) { + if ($classStringParamName !== null) { + return null; + } + $classStringParamName = $paramName; + + continue; + } + + if (DocblockParser::typeReferencesTemplate($typeNode, $templates)) { + return null; + } + + if (! ($typeNode instanceof IdentifierTypeNode)) { + return null; + } + + $checkKind = match (strtolower($typeNode->name)) { + 'bool', 'boolean' => self::PARAM_CHECK_BOOL, + 'int', 'integer' => self::PARAM_CHECK_INT, + 'string' => self::PARAM_CHECK_STRING, + 'float', 'double' => self::PARAM_CHECK_FLOAT, + 'array' => self::PARAM_CHECK_ARRAY, + 'positive-int' => self::PARAM_CHECK_POSITIVE_INT, + 'non-empty-string' => self::PARAM_CHECK_NON_EMPTY_STRING, + 'mixed' => self::PARAM_CHECK_MIXED, + default => null, + }; + + if ($checkKind === null) { + return null; + } + + if ($checkKind !== self::PARAM_CHECK_MIXED) { + $otherParams[] = [$paramName, $checkKind, $typeNode, $sensitiveParams[$paramName] ?? false]; + } + } + + if ($classStringParamName === null) { + return null; + } + + return [ + 'effective' => $effectiveFunction, + 'paramName' => $classStringParamName, + 'templateName' => $tName, + 'otherParams' => $otherParams, + ]; + } + /** * Compiles a simple constructor parameter-to-template plan when all parameters are distinct bare class templates * with no defaults or complex/const bounds. Returns null if the constructor is not eligible. @@ -1257,23 +1500,21 @@ public static function checkSelfOut(string $function, object $thisObj, ?array $v return; } - $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisObj, $thisObj); - - if (isset(SelfOutChecker::$noSelfOutContractCache[$effectiveFunction])) { + if (isset(SelfOutChecker::$noSelfOutContractCache[$function])) { return; } - if (CallerBoundaryResolver::shouldBypass($effectiveFunction)) { + $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisObj, $thisObj); + + if (isset(SelfOutChecker::$noSelfOutContractCache[$effectiveFunction])) { return; } - if (IgnoreManager::isCallerIgnored()) { + if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { return; } - $vars = $vars !== null ? $vars : []; - - SelfOutChecker::checkSelfOut($function, $thisObj, $vars, self::getRegistry(), $effectiveFunction); + SelfOutChecker::checkSelfOut($function, $thisObj, $vars ?? [], self::getRegistry(), $effectiveFunction); } /** @@ -1287,6 +1528,32 @@ public static function checkReturn(string $function, mixed $value, object|string return $value; } + if ( + \is_object($thisOrClass) + && $value === $thisOrClass + && TemplateManager::$instanceTemplateBindings !== null + && isset(TemplateManager::$instanceTemplateBindings[$thisOrClass]) + ) { + if (isset(self::$identitySelfReturnCache[$function]) || isset(self::$traitIdentitySelfReturnCache[$function][$thisOrClass::class])) { + return $value; + } + } + + if ($value === null) { + if (isset(self::$nullableReturnCache[$function])) { + return null; + } + if (\is_object($thisOrClass) && isset(self::$traitNullableReturnCache[$function][$thisOrClass::class])) { + return null; + } + } + + if (\is_object($thisOrClass) && isset(self::$traitReturnPlanCache[$function][$thisOrClass::class])) { + $tPlan = self::$traitReturnPlanCache[$function][$thisOrClass::class]; + + return self::executeSimpleReturnPlan($tPlan['function'], $tPlan['type'], $value, $tPlan['op'], $tPlan['extra']); + } + $retPlan = self::$simpleReturnPlanCache[$function] ?? null; if ( $retPlan !== null @@ -1294,7 +1561,7 @@ public static function checkReturn(string $function, mixed $value, object|string ? $thisOrClass === null : (\is_object($thisOrClass) ? $thisOrClass::class === $retPlan['class'] : $thisOrClass === $retPlan['class'])) ) { - return self::executeSimpleReturnPlan($function, $retPlan['type'], $value); + return self::executeSimpleReturnPlan($function, $retPlan['type'], $value, $retPlan['op'], $retPlan['extra']); } if (isset(self::$genericReturnPlanCache[$function]) && \is_object($thisOrClass)) { @@ -1319,10 +1586,28 @@ public static function checkReturn(string $function, mixed $value, object|string } $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; - $effectiveFunction = ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + $effectiveFunction = $thisOrClass === null + ? $function + : ParamChecker::resolveEffectiveFunction($function, $thisOrClass, $thisObj); + + if ( + $thisObj !== null + && $value === $thisObj + && TemplateManager::$instanceTemplateBindings !== null + && isset(TemplateManager::$instanceTemplateBindings[$thisObj]) + && isset(self::$identitySelfReturnCache[$effectiveFunction]) + ) { + return $value; + } + + if ($value === null && isset(self::$nullableReturnCache[$effectiveFunction])) { + return null; + } if (isset(self::$simpleReturnPlanCache[$effectiveFunction])) { - return self::executeSimpleReturnPlan($effectiveFunction, self::$simpleReturnPlanCache[$effectiveFunction]['type'], $value); + $effPlan = self::$simpleReturnPlanCache[$effectiveFunction]; + + return self::executeSimpleReturnPlan($effectiveFunction, $effPlan['type'], $value, $effPlan['op'], $effPlan['extra']); } if (! isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && CallerBoundaryResolver::shouldBypass($effectiveFunction)) { @@ -1338,19 +1623,51 @@ public static function checkReturn(string $function, mixed $value, object|string $contract = DocblockParser::parse($effectiveFunction); $declaringClass = str_contains($effectiveFunction, '::') ? explode('::', $effectiveFunction, 2)[0] : null; + $returnTypeNode = $contract['return']; + + if (! $isDynamicDispatch && $returnTypeNode === null) { + ReturnChecker::$noReturnContractCache[$effectiveFunction] = true; + + return $value; + } + + if (! $isDynamicDispatch && ($contract['returnAllowsNull'] ?? false) && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { + self::$nullableReturnCache[$effectiveFunction] = true; + if ($function === $effectiveFunction) { + self::$nullableReturnCache[$function] = true; + } elseif ($thisObj !== null && HierarchyResolver::getTraitAliases($thisObj::class) === []) { + self::$traitNullableReturnCache[$function][$thisObj::class] = true; + } + + if ($value === null) { + return null; + } + } if (! $isDynamicDispatch && ($contract['returnUnconstrained'] ?? false)) { - $unconstrainedPlan = ['class' => $declaringClass, 'type' => false]; + ReturnChecker::$noReturnContractCache[$effectiveFunction] = true; + $unconstrainedPlan = [ + 'class' => $declaringClass, + 'type' => false, + 'op' => self::PARAM_CHECK_MIXED, + 'extra' => null, + ]; self::$simpleReturnPlanCache[$effectiveFunction] = $unconstrainedPlan; if ($function === $effectiveFunction) { self::$simpleReturnPlanCache[$function] = $unconstrainedPlan; + } elseif ($thisObj !== null && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && HierarchyResolver::getTraitAliases($thisObj::class) === []) { + self::$traitReturnPlanCache[$function][$thisObj::class] = [ + 'function' => $effectiveFunction, + 'type' => false, + 'op' => self::PARAM_CHECK_MIXED, + 'extra' => null, + ]; } return $value; } $registry = self::$registry ??= new TypeValidatorRegistry(); - $returnTypeNode = $contract['return']; if ( ! $isDynamicDispatch @@ -1367,10 +1684,23 @@ public static function checkReturn(string $function, mixed $value, object|string if ($resolvedType instanceof IdentifierTypeNode) { $lowerName = strtolower($resolvedType->name); if ($lowerName === 'mixed' || $lowerName === 'array') { - $unconstrainedPlan = ['class' => $declaringClass, 'type' => false]; + ReturnChecker::$noReturnContractCache[$effectiveFunction] = true; + $unconstrainedPlan = [ + 'class' => $declaringClass, + 'type' => false, + 'op' => self::PARAM_CHECK_MIXED, + 'extra' => null, + ]; self::$simpleReturnPlanCache[$effectiveFunction] = $unconstrainedPlan; if ($function === $effectiveFunction) { self::$simpleReturnPlanCache[$function] = $unconstrainedPlan; + } elseif ($thisObj !== null && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) && HierarchyResolver::getTraitAliases($thisObj::class) === []) { + self::$traitReturnPlanCache[$function][$thisObj::class] = [ + 'function' => $effectiveFunction, + 'type' => false, + 'op' => self::PARAM_CHECK_MIXED, + 'extra' => null, + ]; } return $value; @@ -1387,10 +1717,23 @@ public static function checkReturn(string $function, mixed $value, object|string } if (! $isTraversableIterable && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { - $compiledPlan = ['class' => $declaringClass, 'type' => $resolvedType]; + [$op, $extra] = self::compileSimpleReturnOp($resolvedType); + $compiledPlan = [ + 'class' => $declaringClass, + 'type' => $resolvedType, + 'op' => $op, + 'extra' => $extra, + ]; self::$simpleReturnPlanCache[$effectiveFunction] = $compiledPlan; if ($function === $effectiveFunction) { self::$simpleReturnPlanCache[$function] = $compiledPlan; + } elseif ($thisObj !== null && HierarchyResolver::getTraitAliases($thisObj::class) === []) { + self::$traitReturnPlanCache[$function][$thisObj::class] = [ + 'function' => $effectiveFunction, + 'type' => $resolvedType, + 'op' => $op, + 'extra' => $extra, + ]; } } @@ -1432,6 +1775,35 @@ public static function checkReturn(string $function, mixed $value, object|string } } + if ( + ! $isDynamicDispatch + && $thisObj !== null + && $declaringClass !== null + && $returnTypeNode instanceof GenericTypeNode + && $contract['templates'] === [] + && $contract['classTemplates'] !== [] + && \count($contract['aliases']) === 0 + && ! ($contract['returnHasConditional'] ?? true) + && ! ($contract['returnIsThis'] ?? false) + && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) + && self::isIdentitySelfGenericReturn($returnTypeNode, $declaringClass, $thisObj, $contract['classTemplates']) + ) { + self::$identitySelfReturnCache[$effectiveFunction] = true; + if ($function === $effectiveFunction) { + self::$identitySelfReturnCache[$function] = true; + } elseif (HierarchyResolver::getTraitAliases($thisObj::class) === []) { + self::$traitIdentitySelfReturnCache[$function][$thisObj::class] = true; + } + + if ( + $value === $thisObj + && TemplateManager::$instanceTemplateBindings !== null + && isset(TemplateManager::$instanceTemplateBindings[$thisObj]) + ) { + return $value; + } + } + $vars = $vars !== null ? $vars : []; $res = ReturnChecker::checkReturn( @@ -1456,9 +1828,95 @@ public static function checkReturn(string $function, mixed $value, object|string return $res; } - private static function executeSimpleReturnPlan(string $function, TypeNode|false $resolvedType, mixed $value): mixed - { - if ($resolvedType === false) { + /** + * Checks whether a GenericTypeNode return contract is an exact identity self-return + * (e.g. `@return self` or `@return static`) matching the class's declared template order. + * + * @param array $classTemplates + */ + private static function isIdentitySelfGenericReturn( + GenericTypeNode $returnTypeNode, + string $declaringClass, + object $thisObj, + array $classTemplates + ): bool { + if ($classTemplates === []) { + return false; + } + + $baseName = (string) $returnTypeNode->type; + $baseLower = strtolower($baseName); + $runtimeClass = $thisObj::class; + + $isSelfRef = match ($baseLower) { + 'self', 'static', '$this' => true, + default => ltrim($baseName, '\\') === $declaringClass || ltrim($baseName, '\\') === $runtimeClass, + }; + + if (! $isSelfRef) { + return false; + } + + $runtimeDeclaredNames = TemplateManager::getDeclaredClassTemplateNames($runtimeClass); + if ($runtimeClass !== $declaringClass && $runtimeDeclaredNames !== []) { + return false; + } + + $targetNames = $runtimeDeclaredNames !== [] ? $runtimeDeclaredNames : array_keys($classTemplates); + if (\count($returnTypeNode->genericTypes) !== \count($targetNames)) { + return false; + } + + foreach ($targetNames as $idx => $tName) { + $gt = $returnTypeNode->genericTypes[$idx] ?? null; + if (! ($gt instanceof IdentifierTypeNode) || $gt->name !== $tName) { + return false; + } + + $variance = $returnTypeNode->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT; + if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { + return false; + } + } + + return true; + } + + private static function executeSimpleReturnPlan( + string $function, + TypeNode|false $resolvedType, + mixed $value, + int $op = self::PARAM_CHECK_FALLBACK, + ?string $extra = null + ): mixed { + if ($resolvedType === false || $op === self::PARAM_CHECK_MIXED) { + return $value; + } + + $ok = match ($op) { + self::PARAM_CHECK_INT => \is_int($value), + self::PARAM_CHECK_STRING => \is_string($value), + self::PARAM_CHECK_BOOL => \is_bool($value), + self::PARAM_CHECK_FLOAT => \is_float($value) || \is_int($value), + self::PARAM_CHECK_ARRAY => \is_array($value), + self::PARAM_CHECK_OBJECT => \is_object($value), + self::PARAM_CHECK_CLASS => \is_object($value) && $extra !== null && ($value instanceof $extra), + self::PARAM_CHECK_POSITIVE_INT => \is_int($value) && $value > 0, + self::PARAM_CHECK_NON_EMPTY_STRING => \is_string($value) && $value !== '', + self::PARAM_CHECK_ARRAY_KEY => \is_int($value) || \is_string($value), + self::PARAM_CHECK_LIST => \is_array($value) && ($value === [] || array_is_list($value)), + self::PARAM_CHECK_NON_NEGATIVE_INT => \is_int($value) && $value >= 0, + self::PARAM_CHECK_NEGATIVE_INT => \is_int($value) && $value < 0, + self::PARAM_CHECK_NON_POSITIVE_INT => \is_int($value) && $value <= 0, + self::PARAM_CHECK_NON_ZERO_INT => \is_int($value) && $value !== 0, + self::PARAM_CHECK_NULL => $value === null, + self::PARAM_CHECK_TRUE => $value === true, + self::PARAM_CHECK_FALSE => $value === false, + self::PARAM_CHECK_SCALAR => \is_scalar($value), + default => false, + }; + + if ($ok) { return $value; } @@ -1477,6 +1935,60 @@ private static function executeSimpleReturnPlan(string $function, TypeNode|false return $value; } + /** + * @return array{0: int, 1: ?string} + */ + private static function compileSimpleReturnOp(TypeNode $resolvedType): array + { + $inner = $resolvedType; + while ($inner instanceof \PHPStan\PhpDocParser\Ast\Type\NullableTypeNode) { + $inner = $inner->type; + } + + if (! ($inner instanceof IdentifierTypeNode)) { + return [self::PARAM_CHECK_FALLBACK, null]; + } + + $name = $inner->name; + + $op = match ($name) { + 'int', 'integer' => self::PARAM_CHECK_INT, + 'string' => self::PARAM_CHECK_STRING, + 'bool', 'boolean' => self::PARAM_CHECK_BOOL, + 'float', 'double' => self::PARAM_CHECK_FLOAT, + 'array' => self::PARAM_CHECK_ARRAY, + 'object' => self::PARAM_CHECK_OBJECT, + 'positive-int' => self::PARAM_CHECK_POSITIVE_INT, + 'non-empty-string' => self::PARAM_CHECK_NON_EMPTY_STRING, + 'array-key' => self::PARAM_CHECK_ARRAY_KEY, + 'list' => self::PARAM_CHECK_LIST, + 'non-negative-int', 'unsigned-int' => self::PARAM_CHECK_NON_NEGATIVE_INT, + 'negative-int' => self::PARAM_CHECK_NEGATIVE_INT, + 'non-positive-int' => self::PARAM_CHECK_NON_POSITIVE_INT, + 'non-zero-int' => self::PARAM_CHECK_NON_ZERO_INT, + 'mixed' => self::PARAM_CHECK_MIXED, + 'null', 'void' => self::PARAM_CHECK_NULL, + 'true' => self::PARAM_CHECK_TRUE, + 'false' => self::PARAM_CHECK_FALSE, + 'scalar' => self::PARAM_CHECK_SCALAR, + default => null, + }; + + if ($op !== null) { + return [$op, null]; + } + + if ( + ! SpecialTypeResolver::isBuiltInTypeKeyword($name) + && ClassNameValidator::isValid($name) + && (class_exists($name, false) || interface_exists($name, false)) + ) { + return [self::PARAM_CHECK_CLASS, $name]; + } + + return [self::PARAM_CHECK_FALLBACK, null]; + } + /** * Validates a value sent into a generator via $gen->send() against TSend. */ diff --git a/src/Internal/Util/ClassNameValidator.php b/src/Internal/Util/ClassNameValidator.php index 8916fdc5..06b61387 100644 --- a/src/Internal/Util/ClassNameValidator.php +++ b/src/Internal/Util/ClassNameValidator.php @@ -17,7 +17,7 @@ final class ClassNameValidator /** * @var array */ - private static array $validClassStringCache = []; + public static array $validClassStringCache = []; public static function reset(): void { diff --git a/src/Internal/Validator/CollectionElementValidator.php b/src/Internal/Validator/CollectionElementValidator.php index 35217738..5bdbe52a 100644 --- a/src/Internal/Validator/CollectionElementValidator.php +++ b/src/Internal/Validator/CollectionElementValidator.php @@ -9,6 +9,9 @@ use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; +use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\RuntimeTypeChecker; +use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; /** @@ -39,7 +42,7 @@ public static function validateElements( $elemName = $elementTypeNode->name; if ($elemName === 'int') { - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } @@ -53,7 +56,7 @@ public static function validateElements( } if ($elemName === 'positive-int') { - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } @@ -67,7 +70,7 @@ public static function validateElements( } if ($elemName === 'string') { - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } @@ -81,7 +84,7 @@ public static function validateElements( } if ($elemName === 'non-empty-string') { - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } @@ -95,7 +98,7 @@ public static function validateElements( } if ($elemName === 'bool') { - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } @@ -109,7 +112,7 @@ public static function validateElements( } if ($elemName === 'float') { - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } @@ -122,12 +125,68 @@ public static function validateElements( return null; } + if ($elemName === 'object') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + + foreach ($items as $k => $v) { + if (! \is_object($v)) { + return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type object, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); + } + } + + return null; + } + + if ($elemName === 'array-key') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + + foreach ($items as $k => $v) { + if (! \is_int($v) && ! \is_string($v)) { + return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type array-key, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); + } + } + + return null; + } + + if ($elemName === 'class-string') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + + foreach ($items as $k => $v) { + if (! \is_string($v) || ! ClassNameValidator::isValidClassString($v)) { + return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type class-string, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); + } + } + + return null; + } + if (\in_array(strtolower($elemName), ['mixed', 't', 'tvalue', 'v', 'value', 'telement'], true)) { return null; } + + if (! SpecialTypeResolver::isBuiltInTypeKeyword($elemName) && (class_exists($elemName, false) || interface_exists($elemName, false))) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + + foreach ($items as $k => $v) { + if (! ($v instanceof $elemName)) { + return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type ' . $elemName . ', ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); + } + } + + return null; + } } - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index af97c5d9..f28a9312 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -20,6 +20,8 @@ use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Generics\TemplateManager; +use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; use WeakMap; @@ -61,7 +63,17 @@ final class GenericValidator implements TypeValidatorInterface ]; /** - * @var WeakMap|null + * @var WeakMap|null */ private static ?WeakMap $compiledGenericCache = null; @@ -169,11 +181,17 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali } if ($kind === self::KIND_ARRAY) { - return $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, false); + /** @var array{mode: int, valType?: TypeNode, keyType?: TypeNode, keyIsArrayKey?: bool, valIsMixed?: bool, isComplexObjectGeneric?: bool, keyFast?: int, valFast?: int, valExtra?: ?string}|null $arrayPlan */ + $arrayPlan = \is_array($compiled[1]) ? $compiled[1] : null; + + return $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, false, $arrayPlan); } if ($kind === self::KIND_NON_EMPTY_ARRAY) { - return $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, true); + /** @var array{mode: int, valType?: TypeNode, keyType?: TypeNode, keyIsArrayKey?: bool, valIsMixed?: bool, isComplexObjectGeneric?: bool, keyFast?: int, valFast?: int, valExtra?: ?string}|null $arrayPlan */ + $arrayPlan = \is_array($compiled[1]) ? $compiled[1] : null; + + return $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, true, $arrayPlan); } if ($kind === self::KIND_INT_RANGE) { @@ -242,7 +260,17 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali } /** - * @return array{0: int, 1: TypeNode|array{0: ?int, 1: ?int}|string|null} + * @return array{0: int, 1: TypeNode|array{0: ?int, 1: ?int}|array{ + * mode: int, + * valType?: TypeNode, + * keyType?: TypeNode, + * keyIsArrayKey?: bool, + * valIsMixed?: bool, + * isComplexObjectGeneric?: bool, + * keyFast?: int, + * valFast?: int, + * valExtra?: ?string + * }|string|null} */ private function compileGeneric(GenericTypeNode $node): array { @@ -254,8 +282,8 @@ private function compileGeneric(GenericTypeNode $node): array return match ($baseType) { 'list' => [self::KIND_LIST, $node->genericTypes[0] ?? null], 'non-empty-list', 'non-empty-array-list' => [self::KIND_NON_EMPTY_LIST, $node->genericTypes[0] ?? null], - 'array', 'iterable', 'traversable', 'generator', 'iterator' => [self::KIND_ARRAY, null], - 'non-empty-array' => [self::KIND_NON_EMPTY_ARRAY, null], + 'array', 'iterable', 'traversable', 'generator', 'iterator' => [self::KIND_ARRAY, self::compileArrayPlan($node)], + 'non-empty-array' => [self::KIND_NON_EMPTY_ARRAY, self::compileArrayPlan($node)], 'int', 'integer' => [ self::KIND_INT_RANGE, [ @@ -275,6 +303,108 @@ private function compileGeneric(GenericTypeNode $node): array }; } + /** + * @return array{ + * mode: int, + * valType?: TypeNode, + * keyType?: TypeNode, + * keyIsArrayKey?: bool, + * valIsMixed?: bool, + * isComplexObjectGeneric?: bool, + * keyFast?: int, + * valFast?: int, + * valExtra?: ?string + * }|null + */ + private static function compileArrayPlan(GenericTypeNode $node): ?array + { + $typesCount = \count($node->genericTypes); + if ($typesCount === 0) { + return null; + } + + if ($typesCount === 1) { + return [ + 'mode' => 1, + 'valType' => $node->genericTypes[0], + ]; + } + + $keyTypeNode = $node->genericTypes[0]; + $valTypeNode = $node->genericTypes[1]; + + $keyIsArrayKey = ($keyTypeNode instanceof IdentifierTypeNode && \in_array(strtolower($keyTypeNode->name), ['array-key', 'mixed', 'tkey', 'key', 'k'], true)) + || ($keyTypeNode instanceof UnionTypeNode && \count($keyTypeNode->types) === 2 && self::isIntStringUnion($keyTypeNode)); + + $valIsMixed = ($valTypeNode instanceof IdentifierTypeNode) && \in_array(strtolower($valTypeNode->name), ['mixed', 'tvalue', 'v', 'value', 't'], true); + + $isComplexObjectGeneric = ($valTypeNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower((string) $valTypeNode->type)])); + + $keyFast = $keyIsArrayKey ? 3 : ($keyTypeNode instanceof IdentifierTypeNode ? match (strtolower($keyTypeNode->name)) { + 'int', 'integer' => 1, + 'string' => 2, + default => 0, + } : 0); + + $valFast = 0; + $valExtra = null; + if ($valIsMixed) { + $valFast = 6; + } elseif ($valTypeNode instanceof IdentifierTypeNode) { + $valName = $valTypeNode->name; + $valLower = strtolower($valName); + $valFast = match ($valLower) { + 'int', 'integer' => 1, + 'string' => 2, + 'bool', 'boolean' => 3, + 'float', 'double' => 4, + 'object' => 5, + 'class-string' => 8, + default => (! SpecialTypeResolver::isBuiltInTypeKeyword($valName) && ClassNameValidator::isValid($valName) && (class_exists($valName, false) || interface_exists($valName, false))) + ? 7 + : 0, + }; + if ($valFast === 7) { + $valExtra = $valName; + } + } + + return [ + 'mode' => 2, + 'keyType' => $keyTypeNode, + 'valType' => $valTypeNode, + 'keyIsArrayKey' => $keyIsArrayKey, + 'valIsMixed' => $valIsMixed, + 'isComplexObjectGeneric' => $isComplexObjectGeneric, + 'keyFast' => $keyFast, + 'valFast' => $valFast, + 'valExtra' => $valExtra, + ]; + } + + private static function isIntStringUnion(UnionTypeNode $node): bool + { + $hasInt = false; + $hasString = false; + + foreach ($node->types as $member) { + if (! ($member instanceof IdentifierTypeNode)) { + return false; + } + + $lower = strtolower($member->name); + if ($lower === 'int' || $lower === 'integer') { + $hasInt = true; + } elseif ($lower === 'string') { + $hasString = true; + } else { + return false; + } + } + + return $hasInt && $hasString; + } + /** * Extracts an integer flag from an int literal or an int BackedEnum case. */ @@ -674,8 +804,28 @@ private function resolveMaskOfPattern(string $className, string $pattern): array return self::$maskOfCache[$cacheKey] = [$allowedMask, $foundFlags]; } - private function validateArray(mixed $value, GenericTypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false, bool $requireNonEmpty = false): ?ErrorMessage - { + /** + * @param array{ + * mode: int, + * valType?: TypeNode, + * keyType?: TypeNode, + * keyIsArrayKey?: bool, + * valIsMixed?: bool, + * isComplexObjectGeneric?: bool, + * keyFast?: int, + * valFast?: int, + * valExtra?: ?string + * }|null $arrayPlan + */ + private function validateArray( + mixed $value, + GenericTypeNode $node, + string $context, + TypeValidatorRegistry $registry, + bool $isSensitive = false, + bool $requireNonEmpty = false, + ?array $arrayPlan = null + ): ?ErrorMessage { if (! \is_array($value) && ! ($value instanceof \Traversable)) { return ErrorFactory::createError($context . ' must be of type ' . (string) $node->type . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } @@ -694,6 +844,27 @@ private function validateArray(mixed $value, GenericTypeNode $node, string $cont return null; } + if ($arrayPlan !== null) { + if ($arrayPlan['mode'] === 1 && isset($arrayPlan['valType'])) { + return $this->validateSingleTypeArray($value, $arrayPlan['valType'], $context, $registry, $isSensitive, $count); + } + + if ($arrayPlan['mode'] === 2 && isset($arrayPlan['keyType'], $arrayPlan['valType'])) { + return $this->validateKeyValueTypeArray( + $value, + $arrayPlan['keyType'], + $arrayPlan['valType'], + $context, + $registry, + $isSensitive, + $count, + $arrayPlan + ); + } + + return null; + } + $typesCount = \count($node->genericTypes); if ($typesCount === 1) { @@ -731,6 +902,17 @@ private function validateSingleTypeArray( /** * @param array $value + * @param array{ + * mode: int, + * valType?: TypeNode, + * keyType?: TypeNode, + * keyIsArrayKey?: bool, + * valIsMixed?: bool, + * isComplexObjectGeneric?: bool, + * keyFast?: int, + * valFast?: int, + * valExtra?: ?string + * }|null $arrayPlan */ private function validateKeyValueTypeArray( array $value, @@ -739,17 +921,54 @@ private function validateKeyValueTypeArray( string $context, TypeValidatorRegistry $registry, bool $isSensitive, - int $count + int $count, + ?array $arrayPlan = null ): ?ErrorMessage { - $keyIsArrayKey = ($keyTypeNode instanceof IdentifierTypeNode) && \in_array(strtolower($keyTypeNode->name), ['array-key', 'mixed', 'tkey', 'key', 'k'], true); - $valIsMixed = ($valTypeNode instanceof IdentifierTypeNode) && \in_array(strtolower($valTypeNode->name), ['mixed', 'tvalue', 'v', 'value', 't'], true); + if ($arrayPlan !== null) { + $keyIsArrayKey = $arrayPlan['keyIsArrayKey'] ?? false; + $valIsMixed = $arrayPlan['valIsMixed'] ?? false; + $isComplexObjectGeneric = $arrayPlan['isComplexObjectGeneric'] ?? false; + $keyFast = $arrayPlan['keyFast'] ?? 0; + $valFast = $arrayPlan['valFast'] ?? 0; + $valExtra = $arrayPlan['valExtra'] ?? null; + } else { + $keyIsArrayKey = ($keyTypeNode instanceof IdentifierTypeNode && \in_array(strtolower($keyTypeNode->name), ['array-key', 'mixed', 'tkey', 'key', 'k'], true)) + || ($keyTypeNode instanceof UnionTypeNode && \count($keyTypeNode->types) === 2 && self::isIntStringUnion($keyTypeNode)); + $valIsMixed = ($valTypeNode instanceof IdentifierTypeNode) && \in_array(strtolower($valTypeNode->name), ['mixed', 'tvalue', 'v', 'value', 't'], true); + $isComplexObjectGeneric = ($valTypeNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower((string) $valTypeNode->type)])); + $keyFast = $keyIsArrayKey ? 3 : ($keyTypeNode instanceof IdentifierTypeNode ? match (strtolower($keyTypeNode->name)) { + 'int', 'integer' => 1, + 'string' => 2, + default => 0, + } : 0); + + $valFast = 0; + $valExtra = null; + if ($valIsMixed) { + $valFast = 6; + } elseif ($valTypeNode instanceof IdentifierTypeNode) { + $valName = $valTypeNode->name; + $valFast = match (strtolower($valName)) { + 'int', 'integer' => 1, + 'string' => 2, + 'bool', 'boolean' => 3, + 'float', 'double' => 4, + 'object' => 5, + 'class-string' => 8, + default => (! SpecialTypeResolver::isBuiltInTypeKeyword($valName) && ClassNameValidator::isValid($valName) && (class_exists($valName, false) || interface_exists($valName, false))) + ? 7 + : 0, + }; + if ($valFast === 7) { + $valExtra = $valName; + } + } + } if ($keyIsArrayKey && $valIsMixed) { return null; } - $isComplexObjectGeneric = ($valTypeNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower((string) $valTypeNode->type)])); - if ($keyIsArrayKey && ! $isComplexObjectGeneric) { return CollectionElementValidator::validateElements( $value, @@ -762,22 +981,7 @@ private function validateKeyValueTypeArray( ); } - $keyFast = $keyIsArrayKey ? 3 : ($keyTypeNode instanceof IdentifierTypeNode ? match ($keyTypeNode->name) { - 'int', 'integer' => 1, - 'string' => 2, - default => 0, - } : 0); - - $valFast = $valIsMixed ? 6 : ($valTypeNode instanceof IdentifierTypeNode ? match ($valTypeNode->name) { - 'int', 'integer' => 1, - 'string' => 2, - 'bool', 'boolean' => 3, - 'float', 'double' => 4, - 'object' => 5, - default => 0, - } : 0); - - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && Config::isArrayValidationHybrid()) { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { $keys = array_keys($value); $sampleKeys = [$keys[0], $keys[$count - 1]]; $samplesToTake = min(3, $count - 2); @@ -807,10 +1011,12 @@ private function validateKeyValueTypeArray( 3 => \is_bool($v), 4 => \is_float($v) || \is_int($v), 5 => \is_object($v), + 7 => \is_object($v) && $valExtra !== null && ($v instanceof $valExtra), + 8 => \is_string($v) && ClassNameValidator::isValidClassString($v), default => false, }; if (! $valOk) { - $err = $isComplexObjectGeneric + $err = ($isComplexObjectGeneric && $valTypeNode instanceof GenericTypeNode) ? $this->validateObjectGeneric($v, $valTypeNode, '', $isSensitive) : $registry->validate($v, $valTypeNode, '', $isSensitive); @@ -844,10 +1050,12 @@ private function validateKeyValueTypeArray( 3 => \is_bool($v), 4 => \is_float($v) || \is_int($v), 5 => \is_object($v), + 7 => \is_object($v) && $valExtra !== null && ($v instanceof $valExtra), + 8 => \is_string($v) && ClassNameValidator::isValidClassString($v), default => false, }; if (! $valOk) { - $err = $isComplexObjectGeneric + $err = ($isComplexObjectGeneric && $valTypeNode instanceof GenericTypeNode) ? $this->validateObjectGeneric($v, $valTypeNode, '', $isSensitive) : $registry->validate($v, $valTypeNode, '', $isSensitive); @@ -916,11 +1124,15 @@ private function resolveIntBound(PhpDocNode $node): ?int private function validateClassString(mixed $value, GenericTypeNode $node, string $context, bool $isSensitive = false): ?ErrorMessage { + $targetClassNode = $node->genericTypes[0] ?? null; + if (\is_string($value) && $targetClassNode instanceof IdentifierTypeNode && isset(self::$classStringBoundCache[$targetClassNode->name][$value])) { + return null; + } + if (! \is_string($value) || ! ClassNameValidator::isValidClassString($value)) { return ErrorFactory::createError($context . ' must be a valid class-string, ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); } - $targetClassNode = $node->genericTypes[0] ?? null; if ($targetClassNode === null) { return null; } diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index 3fc65c48..aff4a807 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -16,6 +16,7 @@ use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Internal\Diagnostic\ErrorMessage; +use TypePHP\Internal\Util\ClassNameValidator; /** * Registry mapping AST TypeNodes to their corresponding validator strategy implementations. @@ -86,11 +87,14 @@ public function validate(mixed $value, TypeNode $node, string $context = '', boo 'non-positive-int' => \is_int($value) && $value <= 0, 'non-zero-int' => \is_int($value) && $value !== 0, 'mixed' => true, - 'null' => $value === null, + 'null', 'void' => $value === null, 'true' => $value === true, 'false' => $value === false, 'scalar' => \is_scalar($value), 'object' => \is_object($value), + 'class-string' => \is_string($value) && ClassNameValidator::isValidClassString($value), + 'iterable' => is_iterable($value), + 'numeric', 'number' => \is_int($value) || \is_float($value) || (\is_string($value) && is_numeric($value)), default => \is_object($value) && ($value instanceof $name), }; diff --git a/src/Internal/Validator/UnionValidator.php b/src/Internal/Validator/UnionValidator.php index 4144c3cd..5a74eb0a 100644 --- a/src/Internal/Validator/UnionValidator.php +++ b/src/Internal/Validator/UnionValidator.php @@ -16,9 +16,11 @@ use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use Stringable; +use Traversable; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; +use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\ClassNameValidator; use WeakMap; @@ -31,16 +33,22 @@ final class UnionValidator implements TypeValidatorInterface * Compiled primitive & literal fast-path sets cached per UnionTypeNode. * * @var WeakMap, - * intLiterals: array + * intLiterals: array, + * classes: list * }>|null */ private static ?WeakMap $compiledUnionCache = null; @@ -53,76 +61,71 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali self::$compiledUnionCache ??= new WeakMap(); $compiled = self::$compiledUnionCache[$unionNode] ??= self::compileUnion($unionNode); - if ($value === null && $compiled['hasNull']) { + if ($compiled['hasMixed']) { return null; } - if (\is_int($value) && ($compiled['hasInt'] || isset($compiled['intLiterals'][$value]))) { + if ($value === null && $compiled['hasNull']) { return null; } - if (\is_string($value) && ($compiled['hasString'] || isset($compiled['stringLiterals'][$value]) || ($compiled['hasClassString'] && ClassNameValidator::isValidClassString($value)))) { + if (\is_int($value) && ($compiled['hasInt'] || $compiled['hasFloat'] || $compiled['hasScalar'] || isset($compiled['intLiterals'][$value]))) { return null; } - if (\is_bool($value) && ($compiled['hasBool'] || ($value ? $compiled['hasTrue'] : $compiled['hasFalse']))) { + if (\is_string($value) && ($compiled['hasString'] || $compiled['hasScalar'] || isset($compiled['stringLiterals'][$value]) || ($compiled['hasClassString'] && ClassNameValidator::isValidClassString($value)))) { return null; } - if (\is_object($value) && $compiled['hasObject']) { + if (\is_bool($value) && ($compiled['hasBool'] || $compiled['hasScalar'] || ($value ? $compiled['hasTrue'] : $compiled['hasFalse']))) { return null; } - foreach ($unionNode->types as $type) { - if ($type instanceof IdentifierTypeNode) { - $name = $type->name; + if (\is_float($value) && ($compiled['hasFloat'] || $compiled['hasScalar'])) { + return null; + } - if ($name === 'object' && \is_object($value)) { - return null; - } - if (($name === 'int' || $name === 'integer') && \is_int($value)) { - return null; - } - if ($name === 'string' && \is_string($value)) { - return null; - } - if (($name === 'bool' || $name === 'boolean') && \is_bool($value)) { - return null; - } - if ($name === 'null' && $value === null) { - return null; - } - if ($name === 'class-string' && \is_string($value) && ClassNameValidator::isValidClassString($value)) { - return null; - } + if (\is_array($value) && ($compiled['hasArray'] || $compiled['hasIterable'])) { + return null; + } - $lower = strtolower($name); - if ($lower === 'object' && \is_object($value)) { - return null; - } - if (($lower === 'int' || $lower === 'integer') && \is_int($value)) { - return null; - } - if ($lower === 'string' && \is_string($value)) { - return null; - } - if (($lower === 'bool' || $lower === 'boolean') && \is_bool($value)) { - return null; - } - if ($lower === 'null' && $value === null) { - return null; - } - if ($lower === 'class-string' && \is_string($value) && ClassNameValidator::isValidClassString($value)) { + $isObj = \is_object($value); + if ($isObj) { + if ($compiled['hasObject'] || ($compiled['hasIterable'] && $value instanceof Traversable)) { + return null; + } + foreach ($compiled['classes'] as $cls) { + if ($value instanceof $cls) { return null; } } } + $isArr = \is_array($value); $deepErrors = []; $discriminatorMatchedErrors = []; $hasAnyDiscriminator = false; foreach ($unionNode->types as $type) { + if ($type instanceof IdentifierTypeNode) { + $tLower = strtolower($type->name); + if ( + ($tLower === 'null' && $value !== null) + || (($tLower === 'int' || $tLower === 'integer') && ! \is_int($value)) + || ($tLower === 'string' && ! \is_string($value)) + || (($tLower === 'bool' || $tLower === 'boolean') && ! \is_bool($value)) + || ($tLower === 'object' && ! $isObj) + || ($tLower === 'array' && ! $isArr) + || (! $isObj && ! SpecialTypeResolver::isBuiltInTypeKeyword($type->name) && ClassNameValidator::isValid($type->name) && (class_exists($type->name, false) || interface_exists($type->name, false))) + ) { + continue; + } + } elseif (! $isObj && $type instanceof ObjectShapeNode) { + continue; + } elseif (! $isArr && $type instanceof ArrayShapeNode) { + continue; + } + $err = $registry->validate($value, $type, $context, $isSensitive); if ($err === null) { return null; @@ -236,34 +239,51 @@ private static function checkDiscriminatorStatus(mixed $value, TypeNode $type): /** * @return array{ + * hasMixed: bool, * hasObject: bool, * hasInt: bool, * hasString: bool, * hasBool: bool, + * hasFloat: bool, * hasNull: bool, * hasTrue: bool, * hasFalse: bool, + * hasArray: bool, + * hasIterable: bool, + * hasScalar: bool, * hasClassString: bool, * stringLiterals: array, - * intLiterals: array + * intLiterals: array, + * classes: list * } */ private static function compileUnion(UnionTypeNode $unionNode): array { + $hasMixed = false; $hasObject = false; $hasInt = false; $hasString = false; $hasBool = false; + $hasFloat = false; $hasNull = false; $hasTrue = false; $hasFalse = false; + $hasArray = false; + $hasIterable = false; + $hasScalar = false; $hasClassString = false; $stringLiterals = []; $intLiterals = []; + $classes = []; foreach ($unionNode->types as $type) { if ($type instanceof IdentifierTypeNode) { - switch (strtolower($type->name)) { + $name = $type->name; + switch (strtolower($name)) { + case 'mixed': + $hasMixed = true; + + break; case 'object': $hasObject = true; @@ -281,6 +301,11 @@ private static function compileUnion(UnionTypeNode $unionNode): array case 'boolean': $hasBool = true; + break; + case 'float': + case 'double': + $hasFloat = true; + break; case 'null': $hasNull = true; @@ -293,10 +318,28 @@ private static function compileUnion(UnionTypeNode $unionNode): array case 'false': $hasFalse = true; + break; + case 'array': + $hasArray = true; + + break; + case 'iterable': + $hasIterable = true; + + break; + case 'scalar': + $hasScalar = true; + break; case 'class-string': $hasClassString = true; + break; + default: + if (! SpecialTypeResolver::isBuiltInTypeKeyword($name) && ClassNameValidator::isValid($name) && (class_exists($name, false) || interface_exists($name, false))) { + $classes[] = $name; + } + break; } } elseif ($type instanceof ConstTypeNode) { @@ -316,16 +359,22 @@ private static function compileUnion(UnionTypeNode $unionNode): array } return [ + 'hasMixed' => $hasMixed, 'hasObject' => $hasObject, 'hasInt' => $hasInt, 'hasString' => $hasString, 'hasBool' => $hasBool, + 'hasFloat' => $hasFloat, 'hasNull' => $hasNull, 'hasTrue' => $hasTrue, 'hasFalse' => $hasFalse, + 'hasArray' => $hasArray, + 'hasIterable' => $hasIterable, + 'hasScalar' => $hasScalar, 'hasClassString' => $hasClassString, 'stringLiterals' => $stringLiterals, 'intLiterals' => $intLiterals, + 'classes' => $classes, ]; } } diff --git a/tests/TypeChecking/Generics/ClosureParameterTemplateOverwritingTest.php b/tests/TypeChecking/Generics/ClosureParameterTemplateOverwritingTest.php index 101cdc51..b6950fa0 100644 --- a/tests/TypeChecking/Generics/ClosureParameterTemplateOverwritingTest.php +++ b/tests/TypeChecking/Generics/ClosureParameterTemplateOverwritingTest.php @@ -133,7 +133,7 @@ public function map(Closure $mapper): ReproBoxCollection expect(fn () => $collection->filter(function (ReproPrimaryKeyStatement $pk): bool { return true; - }))->toThrow(\TypeError::class); + }))->toThrow(TypeError::class); }); }); }); From f92b2a3b7f5a0cce60e9d1050ffc9babc93fbc59 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 22 Nov 2026 15:10:20 +0800 Subject: [PATCH 19/25] Enhance ContractVisitor and NodeBuilder to support class constant checks for protected and private constants, and add tests for validation and transformation of constant visibility --- src/Internal/Ast/ContractVisitor.php | 57 +++++- src/Internal/Ast/NodeBuilder.php | 18 ++ src/Internal/Ast/TypePHPPrinter.php | 4 + src/Internal/RuntimeTypeChecker.php | 26 +++ tests/Internal/Ast/NodeBuilderTest.php | 15 ++ tests/Internal/RuntimeTypeCheckerTest.php | 20 ++ .../Boundaries/AssignOpPrecedenceTest.php | 182 ++++++++++++++++++ .../Boundaries/ConstantContractsTest.php | 140 ++++++++++++++ 8 files changed, 453 insertions(+), 9 deletions(-) create mode 100644 tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 77dcdb32..cfca40b6 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -368,14 +368,19 @@ private function collectUnprovenClassConstantChecks(Node\Stmt\Class_ $node, stri continue; } - $classConstFetch = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName); - - $checkCall = NodeBuilder::createConstantCheckCall( - $fullTarget, - $classConstFetch, - $typeString, - $const->getStartLine() - ); + $checkCall = $stmt->isPublic() + ? NodeBuilder::createConstantCheckCall( + $fullTarget, + new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName), + $typeString, + $const->getStartLine() + ) + : NodeBuilder::createClassConstantCheckCall( + $className, + $constName, + $typeString, + $const->getStartLine() + ); $checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $const->getStartLine())); $checkStmt->setAttribute('typephp_injected', true); @@ -1468,6 +1473,10 @@ private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr return null; } + if (self::rhsNeedsParensInBinaryOp($node->expr)) { + $node->expr->setAttribute('typephp_needs_parens', true); + } + $this->markWriteContext($cleanTarget); return $this->wrapWithPreEvaluations($preAssignments, new Node\Expr\Assign($cleanTarget, $wrapped)); @@ -1476,7 +1485,37 @@ private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr $binaryExpr = new $binaryOpClass($node->var, $node->expr); $wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine()); - return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null; + if ($wrapped === null) { + return null; + } + + if (self::rhsNeedsParensInBinaryOp($node->expr)) { + $node->expr->setAttribute('typephp_needs_parens', true); + } + + return new Node\Expr\Assign($node->var, $wrapped); + } + + private static function rhsNeedsParensInBinaryOp(Node\Expr $expr): bool + { + return $expr instanceof Node\Expr\BinaryOp + || $expr instanceof Node\Expr\Ternary + || $expr instanceof Node\Expr\Assign + || $expr instanceof Node\Expr\AssignOp + || $expr instanceof Node\Expr\AssignRef + || $expr instanceof Node\Expr\Instanceof_ + || $expr instanceof Node\Expr\Cast + || $expr instanceof Node\Expr\UnaryMinus + || $expr instanceof Node\Expr\UnaryPlus + || $expr instanceof Node\Expr\BooleanNot + || $expr instanceof Node\Expr\BitwiseNot + || $expr instanceof Node\Expr\ErrorSuppress + || $expr instanceof Node\Expr\Throw_ + || $expr instanceof Node\Expr\Yield_ + || $expr instanceof Node\Expr\YieldFrom + || $expr instanceof Node\Expr\Print_ + || $expr instanceof Node\Expr\Include_ + || $expr instanceof Node\Expr\ArrowFunction; } private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr diff --git a/src/Internal/Ast/NodeBuilder.php b/src/Internal/Ast/NodeBuilder.php index d954c40d..fdd40402 100644 --- a/src/Internal/Ast/NodeBuilder.php +++ b/src/Internal/Ast/NodeBuilder.php @@ -159,6 +159,24 @@ public static function createPropertyDimAssignCheckCall( ); } + public static function createClassConstantCheckCall( + string $className, + string $constName, + string $typeString, + int $line + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkClassConstant'), + [ + new Node\Arg(new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), 'class')), + new Node\Arg(new Node\Scalar\String_($constName)), + new Node\Arg(new Node\Scalar\String_($typeString)), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ] + ); + } + public static function createConstantCheckCall( string $constantName, Node\Expr $valueExpr, diff --git a/src/Internal/Ast/TypePHPPrinter.php b/src/Internal/Ast/TypePHPPrinter.php index 45df3ac9..b2819da1 100644 --- a/src/Internal/Ast/TypePHPPrinter.php +++ b/src/Internal/Ast/TypePHPPrinter.php @@ -36,6 +36,10 @@ protected function p( int $lhsPrecedence = PrettyPrinterAbstract::MAX_PRECEDENCE, bool $parentFormatPreserved = false ): string { + if ($node->getAttribute('typephp_needs_parens') === true) { + return '(' . parent::p($node, PrettyPrinterAbstract::MAX_PRECEDENCE, PrettyPrinterAbstract::MAX_PRECEDENCE, $parentFormatPreserved) . ')'; + } + $output = parent::p($node, $precedence, $lhsPrecedence, $parentFormatPreserved); if ($node instanceof Node\Stmt && $node->getAttribute('typephp_injected') === true) { diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index e9a645f5..f7e62392 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -295,6 +295,32 @@ public static function checkConstantClosureParam( return $value; } + /** + * Validates non-public (protected/private) class constants via reflection without triggering visibility errors. + * + * @param class-string $className + */ + public static function checkClassConstant( + string $className, + string $constName, + string $typeString, + string $file = '', + ?int $line = null + ): mixed { + if (! self::$isEnabled || ! class_exists($className, false)) { + return null; + } + + try { + $refConst = new \ReflectionClassConstant($className, $constName); + $value = $refConst->getValue(); + } catch (\Throwable) { + return null; + } + + return self::checkConstant($className . '::' . $constName, $value, $typeString, $file, $line); + } + /** * Validates a return value from a constant closure against its return type contract. */ diff --git a/tests/Internal/Ast/NodeBuilderTest.php b/tests/Internal/Ast/NodeBuilderTest.php index 1331515a..db6e6ad7 100644 --- a/tests/Internal/Ast/NodeBuilderTest.php +++ b/tests/Internal/Ast/NodeBuilderTest.php @@ -143,4 +143,19 @@ ->and($call->args[4]->value->value)->toBe(20) ; }); + + test('createClassConstantCheckCall creates FuncCall node for RuntimeTypeChecker::checkClassConstant', function () { + $call = NodeBuilder::createClassConstantCheckCall('App\Example', 'PROTECTED_MAP', 'array', 10); + + expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class) + ->and($call->name->toString())->toBe('TypePHP\Internal\RuntimeTypeChecker::checkClassConstant') + ->and($call->args)->toHaveCount(5) + ->and($call->args[0]->value)->toBeInstanceOf(Node\Expr\ClassConstFetch::class) + ->and($call->args[0]->value->class->toString())->toBe('App\Example') + ->and($call->args[1]->value->value)->toBe('PROTECTED_MAP') + ->and($call->args[2]->value->value)->toBe('array') + ->and($call->args[3]->value)->toBeInstanceOf(Node\Scalar\MagicConst\File::class) + ->and($call->args[4]->value->value)->toBe(10) + ; + }); }); diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index 8a3b016f..a5b0a2a2 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -891,4 +891,24 @@ function vendorAction(): void ->and($violations[0]->kind)->toBe('property') ; }); + + test('checkClassConstant validates protected and private constants via reflection and respects disabled switch', function () { + $class = new class () { + protected const PROT_NUM = 100; + private const PRIV_NUM = -50; + }; + + $className = $class::class; + + $valid = RuntimeTypeChecker::checkClassConstant($className, 'PROT_NUM', 'positive-int', __FILE__, 1); + expect($valid)->toBe(100); + + $invalid = RuntimeTypeChecker::checkClassConstant($className, 'PRIV_NUM', 'positive-int', __FILE__, 2); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain('must be of type positive-int') + ; + + Config::set(['enabled' => false]); + expect(RuntimeTypeChecker::checkClassConstant($className, 'PRIV_NUM', 'positive-int', __FILE__, 2))->toBeNull(); + }); }); diff --git a/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php b/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php new file mode 100644 index 00000000..fe0d18d1 --- /dev/null +++ b/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php @@ -0,0 +1,182 @@ +tooltip ??= $this->direction === 'up' ? 'VALIDATE' : 'CANCEL'; + } +} + +final class AssignOpStrictPropertyFixture +{ + /** + * @var ?non-empty-string + */ + public ?string $tooltip = null; + + public string $direction = 'down'; + + /** + * @var positive-int + */ + public int $multiplier = 4; + + /** + * @var non-empty-string + */ + public string $label = 'prefix'; + + /** + * @var array + */ + public array $slots = [0 => 'existing', 1 => null]; + + public int $indexCalls = 0; + + public function initStrict(bool $useEmptyFallback = false): void + { + $this->tooltip ??= $useEmptyFallback ? '' : ($this->direction === 'up' ? 'VALIDATE' : 'CANCEL'); + } + + public function scale(int $a, int $b): void + { + $this->multiplier *= $a + $b; + } + + public function appendLabel(bool $upper): void + { + $this->label .= $upper ? '_UP' : '_DOWN'; + } + + public function nextIndex(): int + { + return $this->indexCalls++; + } + + public function fillNextSlot(): void + { + $this->slots[$this->nextIndex()] ??= $this->direction === 'up' ? 'VALIDATE' : 'CANCEL'; + } +} + +describe('AssignOp RHS Operator Precedence Preservation', function () { + test('preserves non-null property value when using ??= with a ternary RHS', function () { + $button = new AssignOpButtonFixture(); + $button->tooltip = 'Week tooltip'; + $button->direction = 'down'; + $button->init(); + + expect($button->tooltip)->toBe('Week tooltip'); + + $button->direction = 'up'; + $button->init(); + + expect($button->tooltip)->toBe('Week tooltip'); + }); + + test('evaluates ternary fallback when property is null on ??=', function () { + $downButton = new AssignOpButtonFixture(); + $downButton->direction = 'down'; + $downButton->init(); + + $upButton = new AssignOpButtonFixture(); + $upButton->direction = 'up'; + $upButton->init(); + + expect($downButton->tooltip)->toBe('CANCEL') + ->and($upButton->tooltip)->toBe('VALIDATE') + ; + }); + + test('enforces @var property contract on ??= ternary fallback while preserving existing non-null value', function () { + $preserved = new AssignOpStrictPropertyFixture(); + $preserved->tooltip = 'Existing tooltip'; + $preserved->initStrict(useEmptyFallback: true); + + expect($preserved->tooltip)->toBe('Existing tooltip'); + + $invalid = new AssignOpStrictPropertyFixture(); + expect(fn () => $invalid->initStrict(useEmptyFallback: true)) + ->toThrow(TypeError::class, 'must be of type non-empty-string') + ; + }); + + test('preserves operator precedence for *= and .= with compound RHS on @var properties', function () { + $fixture = new AssignOpStrictPropertyFixture(); + $fixture->scale(2, 3); + $fixture->appendLabel(false); + + expect($fixture->multiplier)->toBe(20) + ->and($fixture->label)->toBe('prefix_DOWN') + ; + }); + + test('preserves operator precedence for ??= and .= with ternary RHS on local @var variables', function () { + /** @var ?non-empty-string $tooltip */ + $tooltip = 'Keep me'; + $direction = 'down'; + $tooltip ??= $direction === 'up' ? 'VALIDATE' : 'CANCEL'; + + expect($tooltip)->toBe('Keep me'); + + /** @var ?non-empty-string $fallback */ + $fallback = null; + $fallback ??= $direction === 'up' ? 'VALIDATE' : 'CANCEL'; + + expect($fallback)->toBe('CANCEL'); + + /** @var non-empty-string $text */ + $text = 'start'; + $flag = false; + $text .= $flag ? '_A' : '_B'; + + expect($text)->toBe('start_B'); + }); + + test('preserves ??= ternary precedence when target array dim expression has side effects', function () { + $fixture = new AssignOpStrictPropertyFixture(); + $fixture->direction = 'down'; + + $fixture->fillNextSlot(); + $fixture->fillNextSlot(); + + expect($fixture->indexCalls)->toBe(2) + ->and($fixture->slots)->toBe([0 => 'existing', 1 => 'CANCEL']) + ; + }); + + test('StreamWrapper parenthesizes ternary RHS when rewriting ??= on properties', function () { + $source = <<<'PHP' +tooltip ??= $this->direction === 'up' ? 'VALIDATE' : 'CANCEL'; + } +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'precedence_button_test.php'); + + expect($transformed)->toContain("\$this->tooltip ?? (\$this->direction === 'up' ? 'VALIDATE' : 'CANCEL')"); + }); +}); diff --git a/tests/TypeChecking/Boundaries/ConstantContractsTest.php b/tests/TypeChecking/Boundaries/ConstantContractsTest.php index 64df25fd..34010d91 100644 --- a/tests/TypeChecking/Boundaries/ConstantContractsTest.php +++ b/tests/TypeChecking/Boundaries/ConstantContractsTest.php @@ -612,4 +612,144 @@ class FixtureReportModeConst } }); }); + + describe('6. Protected and Private Class Constant Visibility', function () { + test('accepts valid protected and private constants without visibility fatal error (User Reproduction)', function () { + $source = <<<'PHP' + */ + protected const PROTECTED_MAP = ['key' => \stdClass::class]; + + /** @var array */ + private const PRIVATE_MAP = ['key' => \stdClass::class]; + + public static function map(): array + { + return [ + 'protected' => self::PROTECTED_MAP, + 'private' => self::PRIVATE_MAP, + ]; + } +} + +return FixtureValidVisibilityConst::map(); +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_vis_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/FixtureValidVisibilityConst.php'; + file_put_contents($filePath, $source); + + try { + StreamWrapper::register(); + + $result = require $filePath; + expect($result)->toBe([ + 'protected' => ['key' => \stdClass::class], + 'private' => ['key' => \stdClass::class], + ]); + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError on invalid protected constant without visibility fatal error', function () { + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'Constant TypePHP\Tests\TypeChecking\Boundaries\FixtureBadProtectedConst::RETRIES must be of type positive-int, negative int (-10) given') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError on invalid private constant without visibility fatal error', function () { + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'Constant TypePHP\Tests\TypeChecking\Boundaries\FixtureBadPrivateConst::SECRET must be of type non-empty-string') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('transforms protected and private constants using checkClassConstant instead of direct fetch', function () { + $source = <<<'PHP' + */ + public const PUBLIC_DATA = ['bad_key' => 'user']; + + /** @var list */ + protected const PROTECTED_DATA = ['bad' => 'val']; + + /** @var list */ + private const PRIVATE_DATA = ['bad' => 'val']; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'ConstTransformVisibilityCheck.php'); + + expect($transformed)->toContain('RuntimeTypeChecker::checkConstant') + ->and($transformed)->toContain('RuntimeTypeChecker::checkClassConstant(\App\ConstTransformVisibilityCheck::class, \'PROTECTED_DATA\'') + ->and($transformed)->toContain('RuntimeTypeChecker::checkClassConstant(\App\ConstTransformVisibilityCheck::class, \'PRIVATE_DATA\'') + ; + }); + }); }); From b535186a6cd9fda655079ce7d7b3f12b2c8060b3 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 22 Nov 2026 16:32:06 +0800 Subject: [PATCH 20/25] Refactor ParamChecker and TemplateManager by improving template binding logic and removing unused methods for cleaner code --- src/Internal/Checker/ParamChecker.php | 17 +++++++++++++---- src/Internal/Generics/TemplateManager.php | 16 ---------------- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 5d4afd6e..a7a66124 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -1479,9 +1479,9 @@ private static function inferArrayTemplatesFromAllElements( } $sampleItems = self::getSampleArraySlice($arrVal); - self::inferSingleTemplateFromArraySamples($tName, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); + $bound = self::inferSingleTemplateFromArraySamples($tName, $sampleItems, $effectiveFunction, $thisObj, $templates, $classTemplates); - return $isPlainArrayOrIterable && TemplateManager::isBound($effectiveFunction, $targetObj, $tName); + return $isPlainArrayOrIterable && $bound; } if ($genericCount === 1 && ($typeNode->genericTypes[0] instanceof ArrayShapeNode || $typeNode->genericTypes[0] instanceof ObjectShapeNode)) { @@ -1817,7 +1817,7 @@ private static function inferSingleTemplateFromArraySamples( ?object $thisObj, array $templates, array $classTemplates = [] - ): void { + ): bool { $valMask = 0; /** @var array $valTypes */ $valTypes = []; @@ -1870,8 +1870,17 @@ private static function inferSingleTemplateFromArraySamples( } if ($inferredType !== null) { - self::bindTemplateIfUnbound($templateName, $inferredType, $effectiveFunction, $thisObj, $templates, $classTemplates); + $isClassLevel = ($thisObj !== null && isset($classTemplates[$templateName]) && ! TemplateManager::isMethodTemplate($effectiveFunction, $templateName)); + $targetObj = $isClassLevel ? $thisObj : null; + + if (self::doesInferredTypeSatisfyBound($templateName, $inferredType, $effectiveFunction, $thisObj, $templates)) { + TemplateManager::bindTemplate($effectiveFunction, $targetObj, $templateName, $inferredType); + + return true; + } } + + return false; } private static function isCollectionTypeNode(TypeNode $node): bool diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 654e2ab5..7c713d9a 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -949,14 +949,6 @@ private static function popActiveCallOrder(string $function): void } } - /** - * @return object|null - */ - private static function getTopCallThis(string $function): ?object - { - return self::$topCallThis[$function] ?? null; - } - /** * Checks whether a template declaration has an F-bound (self-referential upper bound like T of Comparable). */ @@ -3629,14 +3621,6 @@ private static function collectMatchingObjectGenericNodes(object $instance, Type return $matching; } - /** - * Checks whether a function has at least one active call frame on the stack. - */ - private static function hasCallFrame(string $function): bool - { - return isset(self::$topCallFrame[$function]); - } - /** * @return array|null */ From 781422bd180571cc6bef5295faba4790bba7d6db Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 22 Nov 2026 18:30:27 +0800 Subject: [PATCH 21/25] Add tests for cross-namespace imported type alias resolution and related edge cases --- src/Internal/Docblock/DocblockExtractor.php | 32 +++-- src/Internal/Resolver/SpecialTypeResolver.php | 116 +++++++++++++++--- .../ImportedAlias/Child/PaintChildTypes.php | 25 ++++ .../ImportedAlias/Enums/PaintColor.php | 11 ++ .../ImportedAlias/Repo/PaintConsumer.php | 62 ++++++++++ .../Repo/ShadowedAliasConsumer.php | 32 +++++ tests/Fixtures/ImportedAlias/Types/Brush.php | 9 ++ .../ImportedAlias/Types/PaintTypes.php | 18 +++ .../CrossNamespaceImportedTypeAliasTest.php | 84 +++++++++++++ 9 files changed, 360 insertions(+), 29 deletions(-) create mode 100644 tests/Fixtures/ImportedAlias/Child/PaintChildTypes.php create mode 100644 tests/Fixtures/ImportedAlias/Enums/PaintColor.php create mode 100644 tests/Fixtures/ImportedAlias/Repo/PaintConsumer.php create mode 100644 tests/Fixtures/ImportedAlias/Repo/ShadowedAliasConsumer.php create mode 100644 tests/Fixtures/ImportedAlias/Types/Brush.php create mode 100644 tests/Fixtures/ImportedAlias/Types/PaintTypes.php create mode 100644 tests/TypeChecking/ArraysAndShapes/CrossNamespaceImportedTypeAliasTest.php diff --git a/src/Internal/Docblock/DocblockExtractor.php b/src/Internal/Docblock/DocblockExtractor.php index 9c42229c..784097e6 100644 --- a/src/Internal/Docblock/DocblockExtractor.php +++ b/src/Internal/Docblock/DocblockExtractor.php @@ -557,6 +557,7 @@ public static function extractAliases( array &$aliases, \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref ): void { + /** @var array $currentDocAliases */ $currentDocAliases = []; foreach ($phpDocNode->getTagsByName('@psalm-type') as $tag) { @@ -571,12 +572,8 @@ public static function extractAliases( } } - foreach ($currentDocAliases as $name => $type) { - if (! isset($aliases[$name])) { - $aliases[$name] = $type; - } - } - + /** @var array $currentDocImports */ + $currentDocImports = []; $importTags = [ ...$phpDocNode->getTagsByName('@psalm-import-type'), ...$phpDocNode->getTagsByName('@phpstan-import-type'), @@ -587,25 +584,34 @@ public static function extractAliases( $importTag = $tag->value; $localName = $importTag->importedAs ?? $importTag->importedAlias; - if (! isset($aliases[$localName])) { + if (! isset($aliases[$localName]) && ! isset($currentDocAliases[$localName])) { $fqcnSource = SpecialTypeResolver::resolveFqcn((string) $importTag->importedFrom, $ref); $resolvedType = self::resolveImportedTypeAlias($fqcnSource, $importTag->importedAlias); if ($resolvedType !== null) { - $aliases[$localName] = $resolvedType; + $currentDocImports[$localName] = $resolvedType; } } } } - foreach ($aliases as $name => $type) { - $aliases[$name] = DocblockParser::substituteAliases($type, $aliases); + $docScopeAliases = [...$currentDocImports, ...$currentDocAliases]; + foreach ($currentDocAliases as $name => $type) { + $currentDocAliases[$name] = DocblockParser::substituteAliases($type, $docScopeAliases); } - foreach ($currentDocAliases as $name => $_) { - if (isset($aliases[$name])) { - $aliases[$name] = SpecialTypeResolver::resolve($aliases[$name], $ref); + foreach ($currentDocAliases as $name => $type) { + $currentDocAliases[$name] = SpecialTypeResolver::resolve($type, $ref); + } + + foreach ([...$currentDocImports, ...$currentDocAliases] as $name => $type) { + if (! isset($aliases[$name])) { + $aliases[$name] = $type; } } + + foreach ($aliases as $name => $type) { + $aliases[$name] = DocblockParser::substituteAliases($type, $aliases); + } } /** diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 6b44aba1..028c404b 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -189,6 +189,8 @@ final class SpecialTypeResolver */ private static array $fileNamespaceRanges = []; + private const RESOLVED_ATTRIBUTE = 'typephp_resolved'; + /** * Resets reflection context and dynamic caches. Preserves static file imports. */ @@ -225,6 +227,10 @@ public static function checkThisIdentity(TypeNode $returnTypeNode, mixed $value, public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, ?object $thisObj = null): TypeNode { if ($node instanceof IdentifierTypeNode) { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + return $node; + } + $lower = strtolower($node->name); if (isset(self::BUILTIN_TYPE_KEYWORDS[$lower]) && $lower !== 'self' && $lower !== 'parent' && $lower !== 'static' && $lower !== '$this') { if (! isset(self::OVERRIDABLE_SCALAR_ALIASES[$lower]) || $node->name === $lower) { @@ -253,6 +259,10 @@ private static function resolveWithContext( ?object $thisObj = null ): TypeNode { if ($node instanceof IdentifierTypeNode) { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + return $node; + } + $lower = strtolower($node->name); if (isset(self::BUILTIN_TYPE_KEYWORDS[$lower]) && $lower !== 'self' && $lower !== 'parent' && $lower !== 'static' && $lower !== '$this') { if (! isset(self::OVERRIDABLE_SCALAR_ALIASES[$lower]) || $node->name === $lower) { @@ -265,13 +275,13 @@ private static function resolveWithContext( if ($node instanceof ThisTypeNode) { if ($thisObj !== null) { - return new IdentifierTypeNode($thisObj::class); + return self::createResolvedIdentifier($thisObj::class); } if (\is_string($context)) { $callingClass = strstr($context, '::', true); if ($callingClass !== false && self::symbolExists($callingClass)) { - return new IdentifierTypeNode($callingClass); + return self::createResolvedIdentifier($callingClass); } } @@ -396,6 +406,10 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam } if ($node instanceof IdentifierTypeNode) { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + return clone $node; + } + $lower = strtolower($node->name); if (\in_array($lower, ['self', 'static', 'parent', '$this'], strict: true)) { return clone $node; @@ -410,12 +424,28 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam $resolvedClass = self::resolveFqcnForFile($className, $file, true, $namespace); - return $resolvedClass !== $className ? new IdentifierTypeNode($resolvedClass . '::' . $member) : clone $node; + if ( + str_starts_with($className, '\\') + || $resolvedClass !== $className + || (! self::isBuiltInTypeKeyword($resolvedClass) && self::symbolExists($resolvedClass, true)) + ) { + return self::createResolvedIdentifier($resolvedClass . '::' . $member); + } + + return clone $node; } $fqcn = self::resolveFqcnForFile($node->name, $file, true, $namespace); - return $fqcn !== $node->name ? new IdentifierTypeNode($fqcn) : clone $node; + if ( + str_starts_with($node->name, '\\') + || $fqcn !== $node->name + || (! self::isBuiltInTypeKeyword($fqcn) && self::symbolExists($fqcn, true)) + ) { + return self::createResolvedIdentifier($fqcn); + } + + return clone $node; } if ($node instanceof ConstTypeNode) { @@ -560,17 +590,21 @@ private static function resolveIdentifier( \ReflectionClass|\ReflectionFunction|\ReflectionMethod|string $context, ?object $thisObj = null ): IdentifierTypeNode { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + return $node; + } + $lower = strtolower($node->name); if ($lower === '$this') { if ($thisObj !== null) { - return new IdentifierTypeNode($thisObj::class); + return self::createResolvedIdentifier($thisObj::class); } if (\is_string($context)) { $callingClass = strstr($context, '::', true); if ($callingClass !== false && self::symbolExists($callingClass)) { - return new IdentifierTypeNode($callingClass); + return self::createResolvedIdentifier($callingClass); } } @@ -579,13 +613,13 @@ private static function resolveIdentifier( if ($lower === 'static') { if ($thisObj !== null) { - return new IdentifierTypeNode($thisObj::class); + return self::createResolvedIdentifier($thisObj::class); } if (\is_string($context)) { $callingClass = strstr($context, '::', true); if ($callingClass !== false && self::symbolExists($callingClass)) { - return new IdentifierTypeNode($callingClass); + return self::createResolvedIdentifier($callingClass); } } @@ -593,24 +627,24 @@ private static function resolveIdentifier( } if ($lower === 'self' && $declaringClass !== null) { - return new IdentifierTypeNode($declaringClass); + return self::createResolvedIdentifier($declaringClass); } if ($lower === 'parent' && $declaringClass !== null) { $parentClass = get_parent_class($declaringClass); if ($parentClass !== false) { - return new IdentifierTypeNode($parentClass); + return self::createResolvedIdentifier($parentClass); } } if (str_starts_with($lower, 'self::') && $declaringClass !== null) { - return new IdentifierTypeNode($declaringClass . substr($node->name, 4)); + return self::createResolvedIdentifier($declaringClass . substr($node->name, 4)); } if (str_starts_with($lower, 'parent::') && $declaringClass !== null) { $parentClass = get_parent_class($declaringClass); if ($parentClass !== false) { - return new IdentifierTypeNode($parentClass . substr($node->name, 6)); + return self::createResolvedIdentifier($parentClass . substr($node->name, 6)); } } @@ -630,12 +664,36 @@ private static function resolveIdentifier( $resolvedClass = self::resolveFqcn($className, $ref); } - return $resolvedClass !== $className ? new IdentifierTypeNode($resolvedClass . '::' . $member) : $node; + if ( + str_starts_with($className, '\\') + || $resolvedClass !== $className + || (! self::isBuiltInTypeKeyword($resolvedClass) && self::symbolExists($resolvedClass, true)) + ) { + return self::createResolvedIdentifier($resolvedClass . '::' . $member); + } + + return $node; } $fqcn = self::resolveFqcn($node->name, $ref); - return $fqcn !== $node->name ? new IdentifierTypeNode($fqcn) : $node; + if ( + str_starts_with($node->name, '\\') + || $fqcn !== $node->name + || (! self::isBuiltInTypeKeyword($fqcn) && self::symbolExists($fqcn, true)) + ) { + return self::createResolvedIdentifier($fqcn); + } + + return $node; + } + + private static function createResolvedIdentifier(string $name): IdentifierTypeNode + { + $node = new IdentifierTypeNode($name); + $node->setAttribute(self::RESOLVED_ATTRIBUTE, true); + + return $node; } /** @@ -643,6 +701,10 @@ private static function resolveIdentifier( */ private static function resolveConstType(ConstTypeNode $node, ?string $declaringClass, \ReflectionClass|\ReflectionFunction|\ReflectionMethod $ref): ConstTypeNode { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + return $node; + } + if ($node->constExpr instanceof ConstFetchNode && $node->constExpr->className !== '') { $className = $node->constExpr->className; $lowerClassName = strtolower($className); @@ -656,7 +718,16 @@ private static function resolveConstType(ConstTypeNode $node, ?string $declaring $resolvedClass = self::resolveFqcn($className, $ref); } - return new ConstTypeNode(new ConstFetchNode($resolvedClass, $node->constExpr->name)); + $resolvedNode = new ConstTypeNode(new ConstFetchNode($resolvedClass, $node->constExpr->name)); + if ( + str_starts_with($className, '\\') + || $resolvedClass !== $className + || (! self::isBuiltInTypeKeyword($resolvedClass) && self::symbolExists($resolvedClass, true)) + ) { + $resolvedNode->setAttribute(self::RESOLVED_ATTRIBUTE, true); + } + + return $resolvedNode; } return $node; @@ -821,6 +892,10 @@ private static function resolveCallable(CallableTypeNode $node, \ReflectionClass private static function resolveConstTypeForFile(ConstTypeNode $node, string $file, ?string $namespace = null): ConstTypeNode { + if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { + return clone $node; + } + if ($node->constExpr instanceof ConstFetchNode && $node->constExpr->className !== '') { $className = $node->constExpr->className; $lowerClassName = strtolower($className); @@ -831,7 +906,16 @@ private static function resolveConstTypeForFile(ConstTypeNode $node, string $fil $resolvedClass = self::resolveFqcnForFile($className, $file, true, $namespace); } - return new ConstTypeNode(new ConstFetchNode($resolvedClass, $node->constExpr->name)); + $resolvedNode = new ConstTypeNode(new ConstFetchNode($resolvedClass, $node->constExpr->name)); + if ( + str_starts_with($className, '\\') + || $resolvedClass !== $className + || (! self::isBuiltInTypeKeyword($resolvedClass) && self::symbolExists($resolvedClass, true)) + ) { + $resolvedNode->setAttribute(self::RESOLVED_ATTRIBUTE, true); + } + + return $resolvedNode; } return clone $node; diff --git a/tests/Fixtures/ImportedAlias/Child/PaintChildTypes.php b/tests/Fixtures/ImportedAlias/Child/PaintChildTypes.php new file mode 100644 index 00000000..b7f5f8f9 --- /dev/null +++ b/tests/Fixtures/ImportedAlias/Child/PaintChildTypes.php @@ -0,0 +1,25 @@ + $raw + * + * @return PaintArray + */ + public function assignInlineVar(array $raw): array + { + /** @var PaintArray $paint */ + $paint = $raw; + + return $paint; + } +} diff --git a/tests/Fixtures/ImportedAlias/Repo/ShadowedAliasConsumer.php b/tests/Fixtures/ImportedAlias/Repo/ShadowedAliasConsumer.php new file mode 100644 index 00000000..48abc68d --- /dev/null +++ b/tests/Fixtures/ImportedAlias/Repo/ShadowedAliasConsumer.php @@ -0,0 +1,32 @@ + PaintColor::Red]); + + expect($consumer->paint)->toBe(['color' => PaintColor::Red]); + }); + + test('rejects invalid value with resolved FQCN of the declaring file enum', function () { + expect(fn () => new PaintConsumer(['color' => new stdClass()])) + ->toThrow(TypeError::class, "Argument \$paint['color'] must be of type " . PaintColor::class) + ; + }); + + test('resolves aliased use import (use PaintColor as PaletteColor) in declaring file', function () { + $consumer = new PaintConsumer(['color' => PaintColor::Red]); + + expect($consumer->acceptAliased(['color' => PaintColor::Blue])) + ->toBe(['color' => PaintColor::Blue]) + ; + }); + + test('resolves same-namespace class in declaring file without consumer importing it', function () { + $consumer = new PaintConsumer(['color' => PaintColor::Red]); + $brush = new Brush(); + + expect($consumer->acceptSameNamespaceClass(['brush' => $brush])) + ->toBe(['brush' => $brush]) + ; + }); + + test('resolves imported cross-namespace alias on class property and inline @var', function () { + $consumer = new PaintConsumer(['color' => PaintColor::Red]); + + $consumer->savedPaint = ['color' => PaintColor::Blue]; + expect($consumer->savedPaint)->toBe(['color' => PaintColor::Blue]); + + expect($consumer->assignInlineVar(['color' => PaintColor::Red])) + ->toBe(['color' => PaintColor::Red]) + ; + + expect(fn () => $consumer->assignInlineVar(['color' => 'red'])) + ->toThrow(TypeError::class, PaintColor::class) + ; + }); + }); + + describe('2. Related Edge Cases (Expected Red Phase on v0.14.1)', function () { + test('resolves parent alias imports when referenced by a child class @phpstan-type in another namespace', function () { + $child = new PaintChildTypes(); + + $payload = [ + 'paint' => ['color' => PaintColor::Red], + 'qty' => 2, + ]; + + expect($child->acceptExtended($payload))->toBe($payload); + }); + + test('does not re-resolve root-namespace class in imported alias against a shadowing use-alias in consumer', function () { + $consumer = new ShadowedAliasConsumer(); + $now = new DateTimeImmutable(); + + expect($consumer->acceptDate(['at' => $now])) + ->toBe(['at' => $now]) + ; + }); + }); +}); From 60b490b354abdb117a976968157a918a13f461f8 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 22 Nov 2026 19:32:41 +0800 Subject: [PATCH 22/25] Refactor CRLF line-drift test to update parameter type from non-empty-string to string for consistency --- tests/TypeChecking/Boundaries/CrlfLineDriftTest.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php b/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php index df38317d..f86ab9d8 100644 --- a/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php +++ b/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php @@ -16,7 +16,7 @@ . "\r\n" . "/**\r\n" . " * @param positive-int \$id\r\n" - . " * @param non-empty-string \$name\r\n" + . " * @param string \$name\r\n" . " * @return non-empty-string\r\n" . " */\r\n" . "function formatUserData(int \$id, string \$name): string\r\n" @@ -139,8 +139,7 @@ $actualPath = realpath($e->getFile()) !== false ? realpath($e->getFile()) : $e->getFile(); expect(strtolower(str_replace('\\', '/', (string) $actualPath))) - ->toBe(strtolower(str_replace('\\', '/', (string) $expectedPath))) - ; + ->toBe(strtolower(str_replace('\\', '/', (string) $expectedPath))); } finally { @unlink($crlfScriptPath); @rmdir($tempDir); From 48e8836fa825207e5f49b99dee0f784dede317c8 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 22 Nov 2026 20:20:25 +0800 Subject: [PATCH 23/25] Enhance SpecialTypeResolver to support autoload parameter in type resolution methods and update CRLF line-drift test for improved readability --- src/Internal/Ast/FunctionContractInjector.php | 2 +- src/Internal/Resolver/SpecialTypeResolver.php | 102 +++++++++--------- .../Boundaries/CrlfLineDriftTest.php | 3 +- 3 files changed, 56 insertions(+), 51 deletions(-) diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 5810d575..550367a9 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -441,7 +441,7 @@ private static function collectTrustedParamTypes( } if ($currentFile !== '') { - $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile); + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile, null, false); } if ($declaredTemplates !== [] && DocblockParser::typeReferencesTemplate($typeNode, $declaredTemplates)) { diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 028c404b..60fddc8f 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -397,7 +397,7 @@ private static function resolveWithContext( /** * Recursively resolves type identifiers in a TypeNode AST using file context (use imports and namespace). */ - public static function resolveForFile(TypeNode $node, string $file, ?string $namespace = null): TypeNode + public static function resolveForFile(TypeNode $node, string $file, ?string $namespace = null, bool $autoload = true): TypeNode { $file = str_replace('\\', '/', $file); @@ -422,12 +422,12 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam return clone $node; } - $resolvedClass = self::resolveFqcnForFile($className, $file, true, $namespace); + $resolvedClass = self::resolveFqcnForFile($className, $file, $autoload, $namespace); if ( str_starts_with($className, '\\') || $resolvedClass !== $className - || (! self::isBuiltInTypeKeyword($resolvedClass) && self::symbolExists($resolvedClass, true)) + || (! self::isBuiltInTypeKeyword($resolvedClass) && self::symbolExists($resolvedClass, $autoload)) ) { return self::createResolvedIdentifier($resolvedClass . '::' . $member); } @@ -435,12 +435,12 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam return clone $node; } - $fqcn = self::resolveFqcnForFile($node->name, $file, true, $namespace); + $fqcn = self::resolveFqcnForFile($node->name, $file, $autoload, $namespace); if ( str_starts_with($node->name, '\\') || $fqcn !== $node->name - || (! self::isBuiltInTypeKeyword($fqcn) && self::symbolExists($fqcn, true)) + || (! self::isBuiltInTypeKeyword($fqcn) && self::symbolExists($fqcn, $autoload)) ) { return self::createResolvedIdentifier($fqcn); } @@ -449,14 +449,14 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam } if ($node instanceof ConstTypeNode) { - return self::resolveConstTypeForFile($node, $file, $namespace); + return self::resolveConstTypeForFile($node, $file, $namespace, $autoload); } if ($node instanceof GenericTypeNode) { - $genericType = self::resolveForFile($node->type, $file, $namespace); + $genericType = self::resolveForFile($node->type, $file, $namespace, $autoload); $innerTypes = []; foreach ($node->genericTypes as $gt) { - $innerTypes[] = self::resolveForFile($gt, $file, $namespace); + $innerTypes[] = self::resolveForFile($gt, $file, $namespace, $autoload); } return new GenericTypeNode( @@ -467,27 +467,27 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam } if ($node instanceof OffsetAccessTypeNode) { - return self::resolveOffsetAccessForFile($node, $file, $namespace); + return self::resolveOffsetAccessForFile($node, $file, $namespace, $autoload); } if ($node instanceof ArrayShapeNode) { - return self::resolveArrayShapeForFile($node, $file, $namespace); + return self::resolveArrayShapeForFile($node, $file, $namespace, $autoload); } if ($node instanceof ObjectShapeNode) { - return self::resolveObjectShapeForFile($node, $file, $namespace); + return self::resolveObjectShapeForFile($node, $file, $namespace, $autoload); } if ($node instanceof CallableTypeNode) { - return self::resolveCallableForFile($node, $file, $namespace); + return self::resolveCallableForFile($node, $file, $namespace, $autoload); } if ($node instanceof ConditionalTypeNode) { return new ConditionalTypeNode( - self::resolveForFile($node->subjectType, $file, $namespace), - self::resolveForFile($node->targetType, $file, $namespace), - self::resolveForFile($node->if, $file, $namespace), - self::resolveForFile($node->else, $file, $namespace), + self::resolveForFile($node->subjectType, $file, $namespace, $autoload), + self::resolveForFile($node->targetType, $file, $namespace, $autoload), + self::resolveForFile($node->if, $file, $namespace, $autoload), + self::resolveForFile($node->else, $file, $namespace, $autoload), $node->negated ); } @@ -495,25 +495,25 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam if ($node instanceof ConditionalTypeForParameterNode) { return new ConditionalTypeForParameterNode( $node->parameterName, - self::resolveForFile($node->targetType, $file, $namespace), - self::resolveForFile($node->if, $file, $namespace), - self::resolveForFile($node->else, $file, $namespace), + self::resolveForFile($node->targetType, $file, $namespace, $autoload), + self::resolveForFile($node->if, $file, $namespace, $autoload), + self::resolveForFile($node->else, $file, $namespace, $autoload), $node->negated ); } if ($node instanceof NullableTypeNode) { - return new NullableTypeNode(self::resolveForFile($node->type, $file, $namespace)); + return new NullableTypeNode(self::resolveForFile($node->type, $file, $namespace, $autoload)); } if ($node instanceof ArrayTypeNode) { - return new ArrayTypeNode(self::resolveForFile($node->type, $file, $namespace)); + return new ArrayTypeNode(self::resolveForFile($node->type, $file, $namespace, $autoload)); } if ($node instanceof UnionTypeNode) { $types = []; foreach ($node->types as $t) { - $types[] = self::resolveForFile($t, $file, $namespace); + $types[] = self::resolveForFile($t, $file, $namespace, $autoload); } return new UnionTypeNode($types); @@ -522,7 +522,7 @@ public static function resolveForFile(TypeNode $node, string $file, ?string $nam if ($node instanceof IntersectionTypeNode) { $types = []; foreach ($node->types as $t) { - $types[] = self::resolveForFile($t, $file, $namespace); + $types[] = self::resolveForFile($t, $file, $namespace, $autoload); } return new IntersectionTypeNode($types); @@ -890,7 +890,7 @@ private static function resolveCallable(CallableTypeNode $node, \ReflectionClass return new CallableTypeNode($node->identifier, $resolvedParameters, $resolvedReturnType, $resolvedTemplateTypes); } - private static function resolveConstTypeForFile(ConstTypeNode $node, string $file, ?string $namespace = null): ConstTypeNode + private static function resolveConstTypeForFile(ConstTypeNode $node, string $file, ?string $namespace = null, bool $autoload = true): ConstTypeNode { if ($node->getAttribute(self::RESOLVED_ATTRIBUTE) === true) { return clone $node; @@ -903,14 +903,14 @@ private static function resolveConstTypeForFile(ConstTypeNode $node, string $fil if ($lowerClassName === 'self' || $lowerClassName === 'parent') { $resolvedClass = $className; } else { - $resolvedClass = self::resolveFqcnForFile($className, $file, true, $namespace); + $resolvedClass = self::resolveFqcnForFile($className, $file, $autoload, $namespace); } $resolvedNode = new ConstTypeNode(new ConstFetchNode($resolvedClass, $node->constExpr->name)); if ( str_starts_with($className, '\\') || $resolvedClass !== $className - || (! self::isBuiltInTypeKeyword($resolvedClass) && self::symbolExists($resolvedClass, true)) + || (! self::isBuiltInTypeKeyword($resolvedClass) && self::symbolExists($resolvedClass, $autoload)) ) { $resolvedNode->setAttribute(self::RESOLVED_ATTRIBUTE, true); } @@ -921,10 +921,10 @@ private static function resolveConstTypeForFile(ConstTypeNode $node, string $fil return clone $node; } - private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, string $file, ?string $namespace = null): TypeNode + private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, string $file, ?string $namespace = null, bool $autoload = true): TypeNode { - $baseType = self::resolveForFile($node->type, $file, $namespace); - $offsetType = self::resolveForFile($node->offset, $file, $namespace); + $baseType = self::resolveForFile($node->type, $file, $namespace, $autoload); + $offsetType = self::resolveForFile($node->offset, $file, $namespace, $autoload); $offsetKey = self::extractOffsetKey($offsetType); @@ -939,7 +939,7 @@ private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, s } if ($baseType instanceof ConstTypeNode && $baseType->constExpr instanceof ConstFetchNode) { - $resolvedNode = self::resolveConstantOffsetValue($baseType->constExpr->className, $baseType->constExpr->name, $offsetKey); + $resolvedNode = self::resolveConstantOffsetValue($baseType->constExpr->className, $baseType->constExpr->name, $offsetKey, $autoload); if ($resolvedNode !== null) { return $resolvedNode; } @@ -949,7 +949,7 @@ private static function resolveOffsetAccessForFile(OffsetAccessTypeNode $node, s return new OffsetAccessTypeNode($baseType, $offsetType); } - private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $file, ?string $namespace = null): ArrayShapeNode + private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $file, ?string $namespace = null, bool $autoload = true): ArrayShapeNode { $items = []; foreach ($node->items as $item) { @@ -972,8 +972,8 @@ private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $f $lowerClassName = strtolower($className); if ($lowerClassName !== 'self' && $lowerClassName !== 'parent') { - $resolvedClass = self::resolveFqcnForFile($className, $file, true, $namespace); - $resolvedKeyNode = self::resolveConstantKeyValue($resolvedClass, $constName); + $resolvedClass = self::resolveFqcnForFile($className, $file, $autoload, $namespace); + $resolvedKeyNode = self::resolveConstantKeyValue($resolvedClass, $constName, $autoload); if ($resolvedKeyNode !== null) { $keyName = $resolvedKeyNode; } @@ -983,7 +983,7 @@ private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $f $items[] = new ArrayShapeItemNode( $keyName, $item->optional, - self::resolveForFile($item->valueType, $file, $namespace) + self::resolveForFile($item->valueType, $file, $namespace, $autoload) ); } @@ -993,39 +993,39 @@ private static function resolveArrayShapeForFile(ArrayShapeNode $node, string $f $unsealedType = null; if ($node->unsealedType !== null) { - $unsealedKey = $node->unsealedType->keyType !== null ? self::resolveForFile($node->unsealedType->keyType, $file, $namespace) : null; - $unsealedValue = self::resolveForFile($node->unsealedType->valueType, $file, $namespace); + $unsealedKey = $node->unsealedType->keyType !== null ? self::resolveForFile($node->unsealedType->keyType, $file, $namespace, $autoload) : null; + $unsealedValue = self::resolveForFile($node->unsealedType->valueType, $file, $namespace, $autoload); $unsealedType = new ArrayShapeUnsealedTypeNode($unsealedValue, $unsealedKey); } return ArrayShapeNode::createUnsealed($items, $unsealedType, $node->kind); } - private static function resolveObjectShapeForFile(ObjectShapeNode $node, string $file, ?string $namespace = null): ObjectShapeNode + private static function resolveObjectShapeForFile(ObjectShapeNode $node, string $file, ?string $namespace = null, bool $autoload = true): ObjectShapeNode { $items = []; foreach ($node->items as $item) { $items[] = new ObjectShapeItemNode( $item->keyName, $item->optional, - self::resolveForFile($item->valueType, $file, $namespace) + self::resolveForFile($item->valueType, $file, $namespace, $autoload) ); } return new ObjectShapeNode($items); } - private static function resolveCallableForFile(CallableTypeNode $node, string $file, ?string $namespace = null): CallableTypeNode + private static function resolveCallableForFile(CallableTypeNode $node, string $file, ?string $namespace = null, bool $autoload = true): CallableTypeNode { $localTemplates = []; $resolvedTemplateTypes = []; foreach ($node->templateTypes as $tTag) { $localTemplates[$tTag->name] = true; $resolvedBound = $tTag->bound !== null - ? self::resolveForFile($tTag->bound, $file, $namespace) + ? self::resolveForFile($tTag->bound, $file, $namespace, $autoload) : null; $resolvedDefault = $tTag->default !== null - ? self::resolveForFile($tTag->default, $file, $namespace) + ? self::resolveForFile($tTag->default, $file, $namespace, $autoload) : null; $resolvedTemplateTypes[] = new \PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode( $tTag->name, @@ -1039,7 +1039,7 @@ private static function resolveCallableForFile(CallableTypeNode $node, string $f foreach ($node->parameters as $param) { $paramType = ($param->type instanceof IdentifierTypeNode && isset($localTemplates[(string) $param->type])) ? clone $param->type - : self::resolveForFile($param->type, $file, $namespace); + : self::resolveForFile($param->type, $file, $namespace, $autoload); $resolvedParameters[] = new CallableTypeParameterNode( $paramType, @@ -1052,7 +1052,7 @@ private static function resolveCallableForFile(CallableTypeNode $node, string $f $resolvedReturnType = ($node->returnType instanceof IdentifierTypeNode && isset($localTemplates[$node->returnType->name])) ? clone $node->returnType - : self::resolveForFile($node->returnType, $file, $namespace); + : self::resolveForFile($node->returnType, $file, $namespace, $autoload); return new CallableTypeNode($node->identifier, $resolvedParameters, $resolvedReturnType, $resolvedTemplateTypes); } @@ -1093,11 +1093,15 @@ private static function extractItemKey(mixed $keyName): string|int|null /** * Resolves and caches class constant values in memory. */ - private static function getClassConstant(string $fqcn, string $constName): mixed + private static function getClassConstant(string $fqcn, string $constName, bool $autoload = true): mixed { if (! isset(self::$classConstantCache[$fqcn][$constName]) && ! \array_key_exists($constName, self::$classConstantCache[$fqcn] ?? [])) { + if (! $autoload && ! self::symbolExists($fqcn, false)) { + return null; + } + $val = null; - if ($fqcn !== '' && self::symbolExists($fqcn)) { + if ($fqcn !== '' && self::symbolExists($fqcn, $autoload)) { try { /** @var class-string $fqcn */ $refClass = new \ReflectionClass($fqcn); @@ -1113,9 +1117,9 @@ private static function getClassConstant(string $fqcn, string $constName): mixed return self::$classConstantCache[$fqcn][$constName]; } - private static function resolveConstantOffsetValue(string $fqcn, string $constName, string|int $offsetKey): ?TypeNode + private static function resolveConstantOffsetValue(string $fqcn, string $constName, string|int $offsetKey, bool $autoload = true): ?TypeNode { - $constValue = self::getClassConstant($fqcn, $constName); + $constValue = self::getClassConstant($fqcn, $constName, $autoload); if (\is_array($constValue) && \array_key_exists($offsetKey, $constValue)) { $val = $constValue[$offsetKey]; if (\is_string($val)) { @@ -1129,9 +1133,9 @@ private static function resolveConstantOffsetValue(string $fqcn, string $constNa return null; } - public static function resolveConstantKeyValue(string $fqcn, string $constName): ConstExprStringNode|ConstExprIntegerNode|null + public static function resolveConstantKeyValue(string $fqcn, string $constName, bool $autoload = true): ConstExprStringNode|ConstExprIntegerNode|null { - $val = self::getClassConstant($fqcn, $constName); + $val = self::getClassConstant($fqcn, $constName, $autoload); if (\is_string($val)) { return new ConstExprStringNode($val, ConstExprStringNode::SINGLE_QUOTED); } diff --git a/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php b/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php index f86ab9d8..e177562e 100644 --- a/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php +++ b/tests/TypeChecking/Boundaries/CrlfLineDriftTest.php @@ -139,7 +139,8 @@ $actualPath = realpath($e->getFile()) !== false ? realpath($e->getFile()) : $e->getFile(); expect(strtolower(str_replace('\\', '/', (string) $actualPath))) - ->toBe(strtolower(str_replace('\\', '/', (string) $expectedPath))); + ->toBe(strtolower(str_replace('\\', '/', (string) $expectedPath))) + ; } finally { @unlink($crlfScriptPath); @rmdir($tempDir); From 4bf9100b58175feb03e0f0af89fe707a7217f699 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 22 Nov 2026 22:10:18 +0800 Subject: [PATCH 24/25] Refactor CollectionElementValidator and GenericValidator to streamline type validation logic and remove unused SpecialTypeResolver references --- .../Validator/CollectionElementValidator.php | 22 +- src/Internal/Validator/GenericValidator.php | 640 +++++++++--------- 2 files changed, 323 insertions(+), 339 deletions(-) diff --git a/src/Internal/Validator/CollectionElementValidator.php b/src/Internal/Validator/CollectionElementValidator.php index 5bdbe52a..e65811e3 100644 --- a/src/Internal/Validator/CollectionElementValidator.php +++ b/src/Internal/Validator/CollectionElementValidator.php @@ -9,7 +9,6 @@ use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; -use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; @@ -153,13 +152,30 @@ public static function validateElements( return null; } + if ($elemName === 'array') { + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { + return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); + } + + foreach ($items as $k => $v) { + if (! \is_array($v)) { + return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type array, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); + } + } + + return null; + } + if ($elemName === 'class-string') { if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } foreach ($items as $k => $v) { - if (! \is_string($v) || ! ClassNameValidator::isValidClassString($v)) { + if ( + ! \is_string($v) + || ! (ClassNameValidator::$validClassStringCache[$v] ?? ClassNameValidator::isValidClassString($v)) + ) { return ErrorFactory::createError($context . self::formatKey($k, $isList) . ' must be of type class-string, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'); } } @@ -171,7 +187,7 @@ public static function validateElements( return null; } - if (! SpecialTypeResolver::isBuiltInTypeKeyword($elemName) && (class_exists($elemName, false) || interface_exists($elemName, false))) { + if (class_exists($elemName, false) || interface_exists($elemName, false)) { if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { return self::validateHybrid($items, $elementTypeNode, $context, $registry, $count, $isList, $isSensitive); } diff --git a/src/Internal/Validator/GenericValidator.php b/src/Internal/Validator/GenericValidator.php index f28a9312..ed9c1888 100644 --- a/src/Internal/Validator/GenericValidator.php +++ b/src/Internal/Validator/GenericValidator.php @@ -20,7 +20,6 @@ use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; use TypePHP\Internal\Generics\TemplateManager; -use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\RuntimeTypeChecker; use TypePHP\Internal\Util\ClassNameValidator; use TypePHP\Internal\Util\Config; @@ -63,17 +62,7 @@ final class GenericValidator implements TypeValidatorInterface ]; /** - * @var WeakMap|null + * @var WeakMap|null */ private static ?WeakMap $compiledGenericCache = null; @@ -181,17 +170,17 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali } if ($kind === self::KIND_ARRAY) { - /** @var array{mode: int, valType?: TypeNode, keyType?: TypeNode, keyIsArrayKey?: bool, valIsMixed?: bool, isComplexObjectGeneric?: bool, keyFast?: int, valFast?: int, valExtra?: ?string}|null $arrayPlan */ - $arrayPlan = \is_array($compiled[1]) ? $compiled[1] : null; + /** @var array{requireNonEmpty: bool, typesCount: int, baseName: string, keyNode: ?TypeNode, valNode: ?TypeNode, keyIsArrayKey: bool, valIsMixed: bool, keyFast: int, valFast: int, valExtra: ?string, isComplexObjectGeneric: bool} $plan */ + $plan = $compiled[1]; - return $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, false, $arrayPlan); + return $this->validateArrayWithPlan($value, $plan, $context, $registry, $isSensitive); } if ($kind === self::KIND_NON_EMPTY_ARRAY) { - /** @var array{mode: int, valType?: TypeNode, keyType?: TypeNode, keyIsArrayKey?: bool, valIsMixed?: bool, isComplexObjectGeneric?: bool, keyFast?: int, valFast?: int, valExtra?: ?string}|null $arrayPlan */ - $arrayPlan = \is_array($compiled[1]) ? $compiled[1] : null; + /** @var array{requireNonEmpty: bool, typesCount: int, baseName: string, keyNode: ?TypeNode, valNode: ?TypeNode, keyIsArrayKey: bool, valIsMixed: bool, keyFast: int, valFast: int, valExtra: ?string, isComplexObjectGeneric: bool} $plan */ + $plan = $compiled[1]; - return $this->validateArray($value, $genericNode, $context, $registry, $isSensitive, true, $arrayPlan); + return $this->validateArrayWithPlan($value, $plan, $context, $registry, $isSensitive); } if ($kind === self::KIND_INT_RANGE) { @@ -260,17 +249,7 @@ public function validate(mixed $value, TypeNode $node, string $context, TypeVali } /** - * @return array{0: int, 1: TypeNode|array{0: ?int, 1: ?int}|array{ - * mode: int, - * valType?: TypeNode, - * keyType?: TypeNode, - * keyIsArrayKey?: bool, - * valIsMixed?: bool, - * isComplexObjectGeneric?: bool, - * keyFast?: int, - * valFast?: int, - * valExtra?: ?string - * }|string|null} + * @return array{0: int, 1: mixed} */ private function compileGeneric(GenericTypeNode $node): array { @@ -282,8 +261,8 @@ private function compileGeneric(GenericTypeNode $node): array return match ($baseType) { 'list' => [self::KIND_LIST, $node->genericTypes[0] ?? null], 'non-empty-list', 'non-empty-array-list' => [self::KIND_NON_EMPTY_LIST, $node->genericTypes[0] ?? null], - 'array', 'iterable', 'traversable', 'generator', 'iterator' => [self::KIND_ARRAY, self::compileArrayPlan($node)], - 'non-empty-array' => [self::KIND_NON_EMPTY_ARRAY, self::compileArrayPlan($node)], + 'array', 'iterable', 'traversable', 'generator', 'iterator' => [self::KIND_ARRAY, $this->compileArrayPlan($node, $typeName, false)], + 'non-empty-array' => [self::KIND_NON_EMPTY_ARRAY, $this->compileArrayPlan($node, $typeName, true)], 'int', 'integer' => [ self::KIND_INT_RANGE, [ @@ -305,85 +284,153 @@ private function compileGeneric(GenericTypeNode $node): array /** * @return array{ - * mode: int, - * valType?: TypeNode, - * keyType?: TypeNode, - * keyIsArrayKey?: bool, - * valIsMixed?: bool, - * isComplexObjectGeneric?: bool, - * keyFast?: int, - * valFast?: int, - * valExtra?: ?string - * }|null + * requireNonEmpty: bool, + * typesCount: int, + * baseName: string, + * keyNode: ?TypeNode, + * valNode: ?TypeNode, + * keyIsArrayKey: bool, + * valIsMixed: bool, + * keyFast: int, + * valFast: int, + * valExtra: ?string, + * isComplexObjectGeneric: bool + * } */ - private static function compileArrayPlan(GenericTypeNode $node): ?array + private function compileArrayPlan(GenericTypeNode $node, string $baseName, bool $requireNonEmpty): array { $typesCount = \count($node->genericTypes); if ($typesCount === 0) { - return null; + return [ + 'requireNonEmpty' => $requireNonEmpty, + 'typesCount' => 0, + 'baseName' => $baseName, + 'keyNode' => null, + 'valNode' => null, + 'keyIsArrayKey' => true, + 'valIsMixed' => true, + 'keyFast' => 3, + 'valFast' => 6, + 'valExtra' => null, + 'isComplexObjectGeneric' => false, + ]; } if ($typesCount === 1) { + $valNode = $node->genericTypes[0]; + $valIsMixed = $valNode instanceof IdentifierTypeNode + && \in_array(strtolower($valNode->name), ['mixed', 'tvalue', 'v', 'value', 't', 'telement'], true); + return [ - 'mode' => 1, - 'valType' => $node->genericTypes[0], + 'requireNonEmpty' => $requireNonEmpty, + 'typesCount' => 1, + 'baseName' => $baseName, + 'keyNode' => null, + 'valNode' => $valNode, + 'keyIsArrayKey' => true, + 'valIsMixed' => $valIsMixed, + 'keyFast' => 3, + 'valFast' => 0, + 'valExtra' => null, + 'isComplexObjectGeneric' => false, ]; } - $keyTypeNode = $node->genericTypes[0]; - $valTypeNode = $node->genericTypes[1]; - - $keyIsArrayKey = ($keyTypeNode instanceof IdentifierTypeNode && \in_array(strtolower($keyTypeNode->name), ['array-key', 'mixed', 'tkey', 'key', 'k'], true)) - || ($keyTypeNode instanceof UnionTypeNode && \count($keyTypeNode->types) === 2 && self::isIntStringUnion($keyTypeNode)); + $keyNode = $node->genericTypes[0]; + $valNode = $node->genericTypes[1]; - $valIsMixed = ($valTypeNode instanceof IdentifierTypeNode) && \in_array(strtolower($valTypeNode->name), ['mixed', 'tvalue', 'v', 'value', 't'], true); + $keyIsArrayKey = ($keyNode instanceof IdentifierTypeNode && \in_array(strtolower($keyNode->name), ['array-key', 'mixed', 'tkey', 'key', 'k'], true)) + || ($keyNode instanceof UnionTypeNode && self::isIntStringUnion($keyNode)); - $isComplexObjectGeneric = ($valTypeNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower((string) $valTypeNode->type)])); + $keyFast = 0; + if ($keyIsArrayKey) { + $keyFast = 3; + } elseif ($keyNode instanceof IdentifierTypeNode) { + $keyFast = match (strtolower($keyNode->name)) { + 'int', 'integer' => 1, + 'string' => 2, + default => 0, + }; + } - $keyFast = $keyIsArrayKey ? 3 : ($keyTypeNode instanceof IdentifierTypeNode ? match (strtolower($keyTypeNode->name)) { - 'int', 'integer' => 1, - 'string' => 2, - default => 0, - } : 0); + $valIsMixed = $valNode instanceof IdentifierTypeNode + && \in_array(strtolower($valNode->name), ['mixed', 'tvalue', 'v', 'value', 't', 'telement'], true); $valFast = 0; $valExtra = null; + if ($valIsMixed) { $valFast = 6; - } elseif ($valTypeNode instanceof IdentifierTypeNode) { - $valName = $valTypeNode->name; - $valLower = strtolower($valName); - $valFast = match ($valLower) { + } elseif ($valNode instanceof IdentifierTypeNode) { + $vName = $valNode->name; + $vLower = strtolower($vName); + $valFast = match ($vLower) { 'int', 'integer' => 1, 'string' => 2, 'bool', 'boolean' => 3, 'float', 'double' => 4, 'object' => 5, - 'class-string' => 8, - default => (! SpecialTypeResolver::isBuiltInTypeKeyword($valName) && ClassNameValidator::isValid($valName) && (class_exists($valName, false) || interface_exists($valName, false))) - ? 7 - : 0, + 'array' => 7, + 'class-string' => 9, + default => 0, }; - if ($valFast === 7) { - $valExtra = $valName; + + if ($valFast === 0 && ClassNameValidator::isValid($vName) && (class_exists($vName, false) || interface_exists($vName, false))) { + $valFast = 8; + $valExtra = $vName; + } + } elseif ($valNode instanceof UnionTypeNode) { + if (self::isIntStringUnion($valNode)) { + $valFast = 10; + } elseif (\count($valNode->types) === 2) { + $hasNull = false; + $other = null; + foreach ($valNode->types as $m) { + if ($m instanceof IdentifierTypeNode && strtolower($m->name) === 'null') { + $hasNull = true; + } else { + $other = $m; + } + } + if ($hasNull && $other instanceof IdentifierTypeNode) { + $oLower = strtolower($other->name); + if ($oLower === 'string') { + $valFast = 12; + } elseif ($oLower === 'int' || $oLower === 'integer') { + $valFast = 11; + } elseif ($oLower === 'bool' || $oLower === 'boolean') { + $valFast = 13; + } elseif (ClassNameValidator::isValid($other->name) && (class_exists($other->name, false) || interface_exists($other->name, false))) { + $valFast = 14; + $valExtra = $other->name; + } + } } } + $isComplexObjectGeneric = ($valNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower((string) $valNode->type)])); + return [ - 'mode' => 2, - 'keyType' => $keyTypeNode, - 'valType' => $valTypeNode, + 'requireNonEmpty' => $requireNonEmpty, + 'typesCount' => $typesCount, + 'baseName' => $baseName, + 'keyNode' => $keyNode, + 'valNode' => $valNode, 'keyIsArrayKey' => $keyIsArrayKey, 'valIsMixed' => $valIsMixed, - 'isComplexObjectGeneric' => $isComplexObjectGeneric, 'keyFast' => $keyFast, 'valFast' => $valFast, 'valExtra' => $valExtra, + 'isComplexObjectGeneric' => $isComplexObjectGeneric, ]; } private static function isIntStringUnion(UnionTypeNode $node): bool { + if (\count($node->types) !== 2) { + return false; + } + $hasInt = false; $hasString = false; @@ -391,7 +438,6 @@ private static function isIntStringUnion(UnionTypeNode $node): bool if (! ($member instanceof IdentifierTypeNode)) { return false; } - $lower = strtolower($member->name); if ($lower === 'int' || $lower === 'integer') { $hasInt = true; @@ -405,6 +451,192 @@ private static function isIntStringUnion(UnionTypeNode $node): bool return $hasInt && $hasString; } + /** + * @param array{ + * requireNonEmpty: bool, + * typesCount: int, + * baseName: string, + * keyNode: ?TypeNode, + * valNode: ?TypeNode, + * keyIsArrayKey: bool, + * valIsMixed: bool, + * keyFast: int, + * valFast: int, + * valExtra: ?string, + * isComplexObjectGeneric: bool + * } $plan + */ + private function validateArrayWithPlan( + mixed $value, + array $plan, + string $context, + TypeValidatorRegistry $registry, + bool $isSensitive = false + ): ?ErrorMessage { + if (! \is_array($value) && ! ($value instanceof \Traversable)) { + return ErrorFactory::createError($context . ' must be of type ' . $plan['baseName'] . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); + } + + if (! \is_array($value)) { + return null; + } + + $count = \count($value); + + if ($plan['requireNonEmpty'] && $count === 0) { + return ErrorFactory::createError($context . ' must be a non-empty array, empty array given'); + } + + if ($count === 0 || $plan['typesCount'] === 0) { + return null; + } + + if ($plan['typesCount'] === 1) { + if ($plan['valIsMixed'] || $plan['valNode'] === null) { + return null; + } + + return CollectionElementValidator::validateElements( + $value, + $plan['valNode'], + $context, + $registry, + isList: false, + isSensitive: $isSensitive, + count: $count, + ); + } + + $keyFast = $plan['keyFast']; + $valFast = $plan['valFast']; + + if ($keyFast === 3 && $valFast === 6) { + return null; + } + + /** @var TypeNode $valNode */ + $valNode = $plan['valNode']; + /** @var TypeNode $keyNode */ + $keyNode = $plan['keyNode']; + + if ($keyFast === 3 && ! $plan['isComplexObjectGeneric'] && $valFast < 8) { + return CollectionElementValidator::validateElements( + $value, + $valNode, + $context, + $registry, + isList: false, + isSensitive: $isSensitive, + count: $count, + ); + } + + $valExtra = $plan['valExtra']; + $isComplexObjectGeneric = $plan['isComplexObjectGeneric']; + + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { + $keys = array_keys($value); + $sampleKeys = [$keys[0], $keys[$count - 1]]; + $samplesToTake = min(3, $count - 2); + for ($i = 0; $i < $samplesToTake; $i++) { + $sampleKeys[] = $keys[mt_rand(1, $count - 2)]; + } + + foreach ($sampleKeys as $k) { + if ($keyFast !== 3) { + $keyOk = match ($keyFast) { + 1 => \is_int($k), + 2 => \is_string($k), + default => false, + }; + if (! $keyOk) { + $err = $registry->validate($k, $keyNode, ''); + if ($err !== null) { + return ErrorFactory::createError($context . ' key' . $err->getMessage()); + } + } + } + + $v = $value[$k]; + if ($valFast !== 6) { + $valOk = match ($valFast) { + 1 => \is_int($v), + 2 => \is_string($v), + 3 => \is_bool($v), + 4 => \is_float($v) || \is_int($v), + 5 => \is_object($v), + 7 => \is_array($v), + 8 => \is_object($v) && $valExtra !== null && ($v instanceof $valExtra), + 9 => \is_string($v) && (ClassNameValidator::$validClassStringCache[$v] ?? ClassNameValidator::isValidClassString($v)), + 10 => \is_int($v) || \is_string($v), + 11 => $v === null || \is_int($v), + 12 => $v === null || \is_string($v), + 13 => $v === null || \is_bool($v), + 14 => $v === null || (\is_object($v) && $valExtra !== null && ($v instanceof $valExtra)), + default => false, + }; + if (! $valOk) { + $err = ($isComplexObjectGeneric && $valNode instanceof GenericTypeNode) + ? $this->validateObjectGeneric($v, $valNode, '', $isSensitive) + : $registry->validate($v, $valNode, '', $isSensitive); + + if ($err !== null) { + return ErrorFactory::createError($context . "['" . $k . "']" . $err->getMessage()); + } + } + } + } + + return null; + } + + foreach ($value as $k => $v) { + if ($keyFast !== 3) { + $keyOk = match ($keyFast) { + 1 => \is_int($k), + 2 => \is_string($k), + default => false, + }; + if (! $keyOk) { + $err = $registry->validate($k, $keyNode, ''); + if ($err !== null) { + return ErrorFactory::createError($context . ' key' . $err->getMessage()); + } + } + } + + if ($valFast !== 6) { + $valOk = match ($valFast) { + 1 => \is_int($v), + 2 => \is_string($v), + 3 => \is_bool($v), + 4 => \is_float($v) || \is_int($v), + 5 => \is_object($v), + 7 => \is_array($v), + 8 => \is_object($v) && $valExtra !== null && ($v instanceof $valExtra), + 9 => \is_string($v) && (ClassNameValidator::$validClassStringCache[$v] ?? ClassNameValidator::isValidClassString($v)), + 10 => \is_int($v) || \is_string($v), + 11 => $v === null || \is_int($v), + 12 => $v === null || \is_string($v), + 13 => $v === null || \is_bool($v), + 14 => $v === null || (\is_object($v) && $valExtra !== null && ($v instanceof $valExtra)), + default => false, + }; + if (! $valOk) { + $err = ($isComplexObjectGeneric && $valNode instanceof GenericTypeNode) + ? $this->validateObjectGeneric($v, $valNode, '', $isSensitive) + : $registry->validate($v, $valNode, '', $isSensitive); + + if ($err !== null) { + return ErrorFactory::createError($context . "['" . $k . "']" . $err->getMessage()); + } + } + } + } + + return null; + } + /** * Extracts an integer flag from an int literal or an int BackedEnum case. */ @@ -804,270 +1036,6 @@ private function resolveMaskOfPattern(string $className, string $pattern): array return self::$maskOfCache[$cacheKey] = [$allowedMask, $foundFlags]; } - /** - * @param array{ - * mode: int, - * valType?: TypeNode, - * keyType?: TypeNode, - * keyIsArrayKey?: bool, - * valIsMixed?: bool, - * isComplexObjectGeneric?: bool, - * keyFast?: int, - * valFast?: int, - * valExtra?: ?string - * }|null $arrayPlan - */ - private function validateArray( - mixed $value, - GenericTypeNode $node, - string $context, - TypeValidatorRegistry $registry, - bool $isSensitive = false, - bool $requireNonEmpty = false, - ?array $arrayPlan = null - ): ?ErrorMessage { - if (! \is_array($value) && ! ($value instanceof \Traversable)) { - return ErrorFactory::createError($context . ' must be of type ' . (string) $node->type . ', ' . TypeFormatter::formatGivenValue($value, $isSensitive) . ' given'); - } - - if (! \is_array($value)) { - return null; - } - - $count = \count($value); - - if ($requireNonEmpty && $count === 0) { - return ErrorFactory::createError($context . ' must be a non-empty array, empty array given'); - } - - if ($count === 0) { - return null; - } - - if ($arrayPlan !== null) { - if ($arrayPlan['mode'] === 1 && isset($arrayPlan['valType'])) { - return $this->validateSingleTypeArray($value, $arrayPlan['valType'], $context, $registry, $isSensitive, $count); - } - - if ($arrayPlan['mode'] === 2 && isset($arrayPlan['keyType'], $arrayPlan['valType'])) { - return $this->validateKeyValueTypeArray( - $value, - $arrayPlan['keyType'], - $arrayPlan['valType'], - $context, - $registry, - $isSensitive, - $count, - $arrayPlan - ); - } - - return null; - } - - $typesCount = \count($node->genericTypes); - - if ($typesCount === 1) { - return $this->validateSingleTypeArray($value, $node->genericTypes[0], $context, $registry, $isSensitive, $count); - } - - if ($typesCount >= 2) { - return $this->validateKeyValueTypeArray($value, $node->genericTypes[0], $node->genericTypes[1], $context, $registry, $isSensitive, $count); - } - - return null; - } - - /** - * @param array $value - */ - private function validateSingleTypeArray( - array $value, - TypeNode $valTypeNode, - string $context, - TypeValidatorRegistry $registry, - bool $isSensitive, - int $count, - ): ?ErrorMessage { - return CollectionElementValidator::validateElements( - $value, - $valTypeNode, - $context, - $registry, - isList: false, - isSensitive: $isSensitive, - count: $count, - ); - } - - /** - * @param array $value - * @param array{ - * mode: int, - * valType?: TypeNode, - * keyType?: TypeNode, - * keyIsArrayKey?: bool, - * valIsMixed?: bool, - * isComplexObjectGeneric?: bool, - * keyFast?: int, - * valFast?: int, - * valExtra?: ?string - * }|null $arrayPlan - */ - private function validateKeyValueTypeArray( - array $value, - TypeNode $keyTypeNode, - TypeNode $valTypeNode, - string $context, - TypeValidatorRegistry $registry, - bool $isSensitive, - int $count, - ?array $arrayPlan = null - ): ?ErrorMessage { - if ($arrayPlan !== null) { - $keyIsArrayKey = $arrayPlan['keyIsArrayKey'] ?? false; - $valIsMixed = $arrayPlan['valIsMixed'] ?? false; - $isComplexObjectGeneric = $arrayPlan['isComplexObjectGeneric'] ?? false; - $keyFast = $arrayPlan['keyFast'] ?? 0; - $valFast = $arrayPlan['valFast'] ?? 0; - $valExtra = $arrayPlan['valExtra'] ?? null; - } else { - $keyIsArrayKey = ($keyTypeNode instanceof IdentifierTypeNode && \in_array(strtolower($keyTypeNode->name), ['array-key', 'mixed', 'tkey', 'key', 'k'], true)) - || ($keyTypeNode instanceof UnionTypeNode && \count($keyTypeNode->types) === 2 && self::isIntStringUnion($keyTypeNode)); - $valIsMixed = ($valTypeNode instanceof IdentifierTypeNode) && \in_array(strtolower($valTypeNode->name), ['mixed', 'tvalue', 'v', 'value', 't'], true); - $isComplexObjectGeneric = ($valTypeNode instanceof GenericTypeNode && ! isset(self::BUILTIN_GENERICS[strtolower((string) $valTypeNode->type)])); - $keyFast = $keyIsArrayKey ? 3 : ($keyTypeNode instanceof IdentifierTypeNode ? match (strtolower($keyTypeNode->name)) { - 'int', 'integer' => 1, - 'string' => 2, - default => 0, - } : 0); - - $valFast = 0; - $valExtra = null; - if ($valIsMixed) { - $valFast = 6; - } elseif ($valTypeNode instanceof IdentifierTypeNode) { - $valName = $valTypeNode->name; - $valFast = match (strtolower($valName)) { - 'int', 'integer' => 1, - 'string' => 2, - 'bool', 'boolean' => 3, - 'float', 'double' => 4, - 'object' => 5, - 'class-string' => 8, - default => (! SpecialTypeResolver::isBuiltInTypeKeyword($valName) && ClassNameValidator::isValid($valName) && (class_exists($valName, false) || interface_exists($valName, false))) - ? 7 - : 0, - }; - if ($valFast === 7) { - $valExtra = $valName; - } - } - } - - if ($keyIsArrayKey && $valIsMixed) { - return null; - } - - if ($keyIsArrayKey && ! $isComplexObjectGeneric) { - return CollectionElementValidator::validateElements( - $value, - $valTypeNode, - $context, - $registry, - isList: false, - isSensitive: $isSensitive, - count: $count, - ); - } - - if ($count > Config::HYBRID_SAMPLE_THRESHOLD && RuntimeTypeChecker::$arrayValidationHybrid) { - $keys = array_keys($value); - $sampleKeys = [$keys[0], $keys[$count - 1]]; - $samplesToTake = min(3, $count - 2); - for ($i = 0; $i < $samplesToTake; $i++) { - $sampleKeys[] = $keys[mt_rand(1, $count - 2)]; - } - - foreach ($sampleKeys as $k) { - $keyOk = match ($keyFast) { - 3 => true, - 1 => \is_int($k), - 2 => \is_string($k), - default => false, - }; - if (! $keyOk) { - $err = $registry->validate($k, $keyTypeNode, ''); - if ($err !== null) { - return ErrorFactory::createError($context . ' key' . $err->getMessage()); - } - } - - $v = $value[$k]; - $valOk = match ($valFast) { - 6 => true, - 1 => \is_int($v), - 2 => \is_string($v), - 3 => \is_bool($v), - 4 => \is_float($v) || \is_int($v), - 5 => \is_object($v), - 7 => \is_object($v) && $valExtra !== null && ($v instanceof $valExtra), - 8 => \is_string($v) && ClassNameValidator::isValidClassString($v), - default => false, - }; - if (! $valOk) { - $err = ($isComplexObjectGeneric && $valTypeNode instanceof GenericTypeNode) - ? $this->validateObjectGeneric($v, $valTypeNode, '', $isSensitive) - : $registry->validate($v, $valTypeNode, '', $isSensitive); - - if ($err !== null) { - return ErrorFactory::createError($context . "['" . $k . "']" . $err->getMessage()); - } - } - } - - return null; - } - - foreach ($value as $k => $v) { - $keyOk = match ($keyFast) { - 3 => true, - 1 => \is_int($k), - 2 => \is_string($k), - default => false, - }; - if (! $keyOk) { - $err = $registry->validate($k, $keyTypeNode, ''); - if ($err !== null) { - return ErrorFactory::createError($context . ' key' . $err->getMessage()); - } - } - - $valOk = match ($valFast) { - 6 => true, - 1 => \is_int($v), - 2 => \is_string($v), - 3 => \is_bool($v), - 4 => \is_float($v) || \is_int($v), - 5 => \is_object($v), - 7 => \is_object($v) && $valExtra !== null && ($v instanceof $valExtra), - 8 => \is_string($v) && ClassNameValidator::isValidClassString($v), - default => false, - }; - if (! $valOk) { - $err = ($isComplexObjectGeneric && $valTypeNode instanceof GenericTypeNode) - ? $this->validateObjectGeneric($v, $valTypeNode, '', $isSensitive) - : $registry->validate($v, $valTypeNode, '', $isSensitive); - - if ($err !== null) { - return ErrorFactory::createError($context . "['" . $k . "']" . $err->getMessage()); - } - } - } - - return null; - } - private function resolveIntBound(PhpDocNode $node): ?int { if ($node instanceof ConstExprIntegerNode) { From fd779e949013f06fcec9e24b15a8e2a2357bc5b0 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 22 Nov 2026 22:26:18 +0800 Subject: [PATCH 25/25] Refactor RuntimeTypeChecker to enhance type validation logic and improve cache management --- src/Internal/RuntimeTypeChecker.php | 567 ++++++++++++++++++++++++++-- 1 file changed, 534 insertions(+), 33 deletions(-) diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index f7e62392..7db9d7ab 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -4,10 +4,15 @@ namespace TypePHP\Internal; +use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; +use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use PHPStan\PhpDocParser\Parser\TokenIterator; @@ -84,6 +89,18 @@ final class RuntimeTypeChecker private const PARAM_CHECK_CLASS = 20; + private const PARAM_CHECK_NULL_OR_INT = 21; + + private const PARAM_CHECK_NULL_OR_STRING = 22; + + private const PARAM_CHECK_NULL_OR_BOOL = 23; + + private const PARAM_CHECK_REQUIRE_NULL = 24; + + private const PARAM_CHECK_BIND_TEMPLATE = 25; + + private const PARAM_CHECK_INT_OR_FLOAT = 26; + public static bool $isEnabled = true; public static bool $paramsEnabled = true; @@ -170,18 +187,35 @@ final class RuntimeTypeChecker */ private static array $traitIdentitySelfReturnCache = []; + /** + * Compiled fast-path for standalone generic collection functions (e.g. Arr\to_array, Arr\values, Arr\keys, Arr\first). + * + * @var array + * }> + */ + private static array $simpleGenericIterablePlanCache = []; + + private static ?IdentifierTypeNode $arrayKeyNode = null; + /** * Resets runtime caches. */ public static function reset(): void { - self::$identitySelfReturnCache = []; - self::$traitIdentitySelfReturnCache = []; - self::$simpleClassStringTemplatePlanCache = []; self::$traitScopePlanCache = []; self::$traitReturnPlanCache = []; self::$nullableReturnCache = []; self::$traitNullableReturnCache = []; + self::$simpleClassStringTemplatePlanCache = []; + self::$identitySelfReturnCache = []; + self::$traitIdentitySelfReturnCache = []; + self::$simpleGenericIterablePlanCache = []; self::$simpleScopePlanCache = []; self::$simpleCtorTemplatePlanCache = []; self::$simpleReturnPlanCache = []; @@ -206,6 +240,32 @@ public static function isEnabled(): bool return Config::isEnabled(); } + /** + * Validates non-public (protected/private) class constants via reflection without triggering visibility errors. + * + * @param class-string $className + */ + public static function checkClassConstant( + string $className, + string $constName, + string $typeString, + string $file = '', + ?int $line = null + ): mixed { + if (! self::$isEnabled || ! class_exists($className, false)) { + return null; + } + + try { + $refConst = new \ReflectionClassConstant($className, $constName); + $value = $refConst->getValue(); + } catch (\Throwable) { + return null; + } + + return self::checkConstant($className . '::' . $constName, $value, $typeString, $file, $line); + } + /** * Validates class-level and global constants against declared @var contracts upon declaration/load. */ @@ -295,32 +355,6 @@ public static function checkConstantClosureParam( return $value; } - /** - * Validates non-public (protected/private) class constants via reflection without triggering visibility errors. - * - * @param class-string $className - */ - public static function checkClassConstant( - string $className, - string $constName, - string $typeString, - string $file = '', - ?int $line = null - ): mixed { - if (! self::$isEnabled || ! class_exists($className, false)) { - return null; - } - - try { - $refConst = new \ReflectionClassConstant($className, $constName); - $value = $refConst->getValue(); - } catch (\Throwable) { - return null; - } - - return self::checkConstant($className . '::' . $constName, $value, $typeString, $file, $line); - } - /** * Validates a return value from a constant closure against its return type contract. */ @@ -911,6 +945,128 @@ public static function setupScope(string $function, array $vars, object|string|n } } + if ($thisOrClass === null && isset(self::$simpleGenericIterablePlanCache[$function])) { + $gaPlan = self::$simpleGenericIterablePlanCache[$function]; + $pName = $gaPlan['primaryParam']; + + if (isset($vars[$pName]) && \is_array($vars[$pName])) { + $boundTemplates = []; + $otherOk = true; + + foreach ($gaPlan['otherParams'] as $op) { + $opName = $op[0]; + if (isset($vars[$opName])) { + $ov = $vars[$opName]; + } elseif (\array_key_exists($opName, $vars)) { + $ov = null; + } else { + continue; + } + + $opKind = $op[1]; + if ($opKind === self::PARAM_CHECK_BIND_TEMPLATE) { + /** @var string $btName */ + $btName = $op[2]; + $boundTemplates[$btName] = self::fastInferType($ov); + + continue; + } + + $ok = match ($opKind) { + self::PARAM_CHECK_BOOL => \is_bool($ov), + self::PARAM_CHECK_INT => \is_int($ov), + self::PARAM_CHECK_STRING => \is_string($ov), + self::PARAM_CHECK_FLOAT => \is_float($ov) || \is_int($ov), + self::PARAM_CHECK_INT_OR_FLOAT => \is_int($ov) || \is_float($ov), + self::PARAM_CHECK_NULL_OR_INT => $ov === null || \is_int($ov), + self::PARAM_CHECK_NULL_OR_STRING => $ov === null || \is_string($ov), + self::PARAM_CHECK_NULL_OR_BOOL => $ov === null || \is_bool($ov), + self::PARAM_CHECK_REQUIRE_NULL => $ov === null, + self::PARAM_CHECK_ARRAY_KEY => \is_int($ov) || \is_string($ov), + self::PARAM_CHECK_ARRAY => \is_array($ov), + self::PARAM_CHECK_MIXED => true, + default => false, + }; + + if (! $ok) { + $otherOk = false; + + break; + } + } + + if ($otherOk) { + $arr = $vars[$pName]; + $count = \count($arr); + + if ($count > 0 && ($gaPlan['needsKey'] || $gaPlan['needsVal'])) { + $needK = $gaPlan['needsKey']; + $needV = $gaPlan['needsVal']; + $keyMask = 0; + $valMask = 0; + /** @var array $valTypes */ + $valTypes = []; + + if ($count > Config::HYBRID_SAMPLE_THRESHOLD && self::$arrayValidationHybrid) { + $keys = array_keys($arr); + $sampleKeys = [$keys[0], $keys[$count - 1]]; + $samplesToTake = min(3, $count - 2); + for ($i = 0; $i < $samplesToTake; $i++) { + $sampleKeys[] = $keys[mt_rand(1, $count - 2)]; + } + + foreach ($sampleKeys as $k) { + if ($needK) { + $keyMask |= \is_int($k) ? 1 : 2; + } + if ($needV) { + self::accumulateInferredSample($arr[$k], $valMask, $valTypes); + } + } + } else { + foreach ($arr as $k => $v) { + if ($needK) { + $keyMask |= \is_int($k) ? 1 : 2; + if (! $needV && $keyMask === 3) { + break; + } + } + if ($needV) { + self::accumulateInferredSample($v, $valMask, $valTypes); + } + } + } + + if ($needK && $keyMask !== 0 && $gaPlan['keyTName'] !== null) { + $boundTemplates[$gaPlan['keyTName']] = match ($keyMask) { + 1 => TemplateManager::$intNode ??= new IdentifierTypeNode('int'), + 2 => TemplateManager::$stringNode ??= new IdentifierTypeNode('string'), + default => self::$arrayKeyNode ??= new IdentifierTypeNode('array-key'), + }; + } + + if ($needV && ($valMask !== 0 || $valTypes !== []) && $gaPlan['valTName'] !== null) { + $boundTemplates[$gaPlan['valTName']] = self::buildFastValueTypeNode($valMask, $valTypes); + } + } + + if (isset(TemplateManager::$topCallFrame[$function])) { + TemplateManager::pushCallFrame($function, null); + TemplateManager::$topCallFrame[$function] = $boundTemplates; + } else { + TemplateManager::$topCallFrame[$function] = $boundTemplates; + TemplateManager::$topCallThis[$function] = null; + TemplateManager::$activeCallOrder[] = $function; + } + + $cleaner = new ScopeCleaner($function); + $cleaner->boundTemplates = $boundTemplates; + + return $cleaner; + } + } + } + $plan = self::$simpleScopePlanCache[$function] ?? null; if ( @@ -1078,6 +1234,26 @@ public static function setupScope(string $function, array $vars, object|string|n } } + if ( + $thisOrClass === null + && ! $isMagicCall + && ! str_contains($effectiveFunction, '::') + && $contract['classTemplates'] === [] + && $contract['templates'] !== [] + && $contract['aliases'] === [] + && ! $contract['paramsAreDynamic'] + && ! $contract['hasParamOutContract'] + && ($contract['paramConditionals'] ?? []) === [] + && ! ($contract['hasCrossReferencedBounds'] ?? true) + && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction]) + && ! isset(self::$simpleGenericIterablePlanCache[$effectiveFunction]) + ) { + $gaCompiled = self::compileSimpleGenericIterablePlan($contract); + if ($gaCompiled !== null) { + self::$simpleGenericIterablePlanCache[$effectiveFunction] = $gaCompiled; + } + } + $err = ParamChecker::checkParams( $function, $vars, @@ -1125,9 +1301,334 @@ public static function setupScope(string $function, array $vars, object|string|n return null; } + private static function fastInferType(mixed $val): TypeNode + { + if (\is_string($val)) { + return TemplateManager::$stringNode ??= new IdentifierTypeNode('string'); + } + if (\is_int($val)) { + return TemplateManager::$intNode ??= new IdentifierTypeNode('int'); + } + if ($val === null) { + return new IdentifierTypeNode('null'); + } + if (\is_bool($val)) { + return TemplateManager::$boolNode ??= new IdentifierTypeNode('bool'); + } + if (\is_float($val)) { + return TemplateManager::$floatNode ??= new IdentifierTypeNode('float'); + } + if (\is_object($val) && (TemplateManager::$instanceTemplateBindings === null || ! isset(TemplateManager::$instanceTemplateBindings[$val]))) { + $cls = $val::class; + + return TemplateManager::$classNodeCache[$cls] ??= new IdentifierTypeNode($cls); + } + + return TemplateManager::inferTypeFromValue($val); + } + + /** + * @param array $valTypes + */ + private static function accumulateInferredSample(mixed $item, int &$valMask, array &$valTypes): void + { + if (\is_string($item)) { + $valMask |= 2; + } elseif (\is_int($item)) { + $valMask |= 1; + } elseif (\is_bool($item)) { + $valMask |= 4; + } elseif (\is_float($item)) { + $valMask |= 8; + } elseif ($item === null) { + $valMask |= 16; + } elseif (\is_object($item)) { + if (TemplateManager::$instanceTemplateBindings !== null && isset(TemplateManager::$instanceTemplateBindings[$item])) { + $objType = TemplateManager::inferTypeFromValue($item); + $valTypes[(string) $objType] = $objType; + } else { + $cls = $item::class; + if (! isset($valTypes[$cls])) { + $valTypes[$cls] = TemplateManager::$classNodeCache[$cls] ??= new IdentifierTypeNode($cls); + } + } + } else { + $itemType = TemplateManager::inferTypeFromValue($item); + $valTypes[(string) $itemType] = $itemType; + } + } + + /** + * @param array $valTypes + */ + private static function buildFastValueTypeNode(int $valMask, array $valTypes): TypeNode + { + if ($valTypes === []) { + if ($valMask === 2) { + return TemplateManager::$stringNode ??= new IdentifierTypeNode('string'); + } + if ($valMask === 1) { + return TemplateManager::$intNode ??= new IdentifierTypeNode('int'); + } + if ($valMask === 4) { + return TemplateManager::$boolNode ??= new IdentifierTypeNode('bool'); + } + if ($valMask === 8) { + return TemplateManager::$floatNode ??= new IdentifierTypeNode('float'); + } + } + + if (($valMask & 1) !== 0 && ! isset($valTypes['int'])) { + $valTypes['int'] = TemplateManager::$intNode ??= new IdentifierTypeNode('int'); + } + if (($valMask & 2) !== 0 && ! isset($valTypes['string'])) { + $valTypes['string'] = TemplateManager::$stringNode ??= new IdentifierTypeNode('string'); + } + if (($valMask & 4) !== 0 && ! isset($valTypes['bool'])) { + $valTypes['bool'] = TemplateManager::$boolNode ??= new IdentifierTypeNode('bool'); + } + if (($valMask & 8) !== 0 && ! isset($valTypes['float'])) { + $valTypes['float'] = TemplateManager::$floatNode ??= new IdentifierTypeNode('float'); + } + if (($valMask & 16) !== 0 && ! isset($valTypes['null'])) { + $valTypes['null'] = new IdentifierTypeNode('null'); + } + + $values = array_values($valTypes); + + return \count($values) === 1 ? $values[0] : new UnionTypeNode($values); + } + + /** + * @param array{ + * types: array, + * templates: array, + * return: ?TypeNode + * } $contract + * + * @return ?array{ + * primaryParam: string, + * keyTName: ?string, + * valTName: ?string, + * needsKey: bool, + * needsVal: bool, + * otherParams: list + * } + */ + private static function compileSimpleGenericIterablePlan(array $contract): ?array + { + $templates = $contract['templates']; + + foreach ($templates as $tTag) { + if ($tTag->default !== null) { + return null; + } + if ($tTag->bound !== null) { + if (! ($tTag->bound instanceof IdentifierTypeNode) || strtolower($tTag->bound->name) !== 'array-key') { + return null; + } + } + } + + $primaryParam = null; + $keyTName = null; + $valTName = null; + + foreach ($contract['types'] as $pName => $tNode) { + $foundGeneric = null; + if ($tNode instanceof GenericTypeNode) { + $base = strtolower((string) $tNode->type); + if ($base === 'array' || $base === 'iterable') { + $foundGeneric = $tNode; + } else { + return null; + } + } elseif ($tNode instanceof UnionTypeNode) { + foreach ($tNode->types as $member) { + if ($member instanceof ArrayShapeNode || $member instanceof ObjectShapeNode || $member instanceof ArrayTypeNode || $member instanceof CallableTypeNode) { + return null; + } + if ($member instanceof GenericTypeNode) { + $mBase = strtolower((string) $member->type); + if ($mBase === 'array' || $mBase === 'iterable') { + $foundGeneric ??= $member; + } else { + return null; + } + } + } + } + + if ($foundGeneric !== null) { + if ($primaryParam !== null) { + return null; + } + + $gtCount = \count($foundGeneric->genericTypes); + if ($gtCount === 1) { + $gt0 = $foundGeneric->genericTypes[0]; + if (! ($gt0 instanceof IdentifierTypeNode) || ! isset($templates[$gt0->name])) { + return null; + } + $valTName = $gt0->name; + } elseif ($gtCount === 2) { + $gt0 = $foundGeneric->genericTypes[0]; + $gt1 = $foundGeneric->genericTypes[1]; + + if ($gt0 instanceof IdentifierTypeNode && isset($templates[$gt0->name])) { + $keyTName = $gt0->name; + } elseif (! ($gt0 instanceof IdentifierTypeNode) || ! \in_array(strtolower($gt0->name), ['array-key', 'mixed'], true)) { + return null; + } + + if (! ($gt1 instanceof IdentifierTypeNode) || ! isset($templates[$gt1->name])) { + return null; + } + $valTName = $gt1->name; + } else { + return null; + } + + $primaryParam = $pName; + } + } + + if ($primaryParam === null) { + return null; + } + + $otherParams = []; + $usedElsewhere = []; + if ($contract['return'] !== null) { + foreach ($templates as $tName => $_) { + if (DocblockParser::typeReferencesTemplate($contract['return'], [$tName => true])) { + $usedElsewhere[$tName] = true; + } + } + } else { + foreach ($templates as $tName => $_) { + $usedElsewhere[$tName] = true; + } + } + + foreach ($contract['types'] as $pName => $tNode) { + if ($pName === $primaryParam) { + continue; + } + + if ($tNode instanceof IdentifierTypeNode && isset($templates[$tNode->name])) { + $btName = $tNode->name; + if ($btName === $keyTName || $btName === $valTName || $templates[$btName]->bound !== null) { + return null; + } + $otherParams[] = [$pName, self::PARAM_CHECK_BIND_TEMPLATE, $btName]; + + continue; + } + + if ($tNode instanceof CallableTypeNode) { + return null; + } + + if ($tNode instanceof NullableTypeNode) { + if ($tNode->type instanceof CallableTypeNode) { + $otherParams[] = [$pName, self::PARAM_CHECK_REQUIRE_NULL, null]; + + continue; + } + if ($tNode->type instanceof IdentifierTypeNode) { + $op = match (strtolower($tNode->type->name)) { + 'int', 'integer' => self::PARAM_CHECK_NULL_OR_INT, + 'string' => self::PARAM_CHECK_NULL_OR_STRING, + 'bool', 'boolean' => self::PARAM_CHECK_NULL_OR_BOOL, + 'closure' => self::PARAM_CHECK_REQUIRE_NULL, + default => null, + }; + if ($op === null) { + return null; + } + $otherParams[] = [$pName, $op, null]; + + continue; + } + + return null; + } + + if ($tNode instanceof UnionTypeNode) { + if (\count($tNode->types) === 2) { + $t0 = $tNode->types[0]; + $t1 = $tNode->types[1]; + if ($t0 instanceof IdentifierTypeNode && $t1 instanceof IdentifierTypeNode) { + $n0 = strtolower($t0->name); + $n1 = strtolower($t1->name); + if (($n0 === 'int' && $n1 === 'float') || ($n0 === 'float' && $n1 === 'int')) { + $otherParams[] = [$pName, self::PARAM_CHECK_INT_OR_FLOAT, null]; + + continue; + } + if ($n1 === 'null' || $n0 === 'null') { + $otherName = $n1 === 'null' ? $n0 : $n1; + $op = match ($otherName) { + 'int', 'integer' => self::PARAM_CHECK_NULL_OR_INT, + 'string' => self::PARAM_CHECK_NULL_OR_STRING, + 'bool', 'boolean' => self::PARAM_CHECK_NULL_OR_BOOL, + 'closure' => self::PARAM_CHECK_REQUIRE_NULL, + default => null, + }; + if ($op !== null) { + $otherParams[] = [$pName, $op, null]; + + continue; + } + } + } + if (($t0 instanceof CallableTypeNode && $t1 instanceof IdentifierTypeNode && strtolower($t1->name) === 'null') + || ($t1 instanceof CallableTypeNode && $t0 instanceof IdentifierTypeNode && strtolower($t0->name) === 'null')) { + $otherParams[] = [$pName, self::PARAM_CHECK_REQUIRE_NULL, null]; + + continue; + } + } + + return null; + } + + if ($tNode instanceof IdentifierTypeNode) { + $op = match (strtolower($tNode->name)) { + 'int', 'integer' => self::PARAM_CHECK_INT, + 'string' => self::PARAM_CHECK_STRING, + 'bool', 'boolean' => self::PARAM_CHECK_BOOL, + 'float', 'double' => self::PARAM_CHECK_FLOAT, + 'array-key' => self::PARAM_CHECK_ARRAY_KEY, + 'array' => self::PARAM_CHECK_ARRAY, + 'mixed' => self::PARAM_CHECK_MIXED, + default => null, + }; + if ($op === null) { + return null; + } + $otherParams[] = [$pName, $op, null]; + + continue; + } + + return null; + } + + return [ + 'primaryParam' => $primaryParam, + 'keyTName' => $keyTName, + 'valTName' => $valTName, + 'needsKey' => $keyTName !== null && isset($usedElsewhere[$keyTName]), + 'needsVal' => $valTName !== null && isset($usedElsewhere[$valTName]), + 'otherParams' => $otherParams, + ]; + } + /** * @param array $types - * @param array $templates + * @param array $templates * @param array $sensitiveParams * * @return array{effective: string, paramName: string, templateName: string, otherParams: list}|null @@ -1219,7 +1720,7 @@ private static function compileSimpleClassStringTemplatePlan( * with no defaults or complex/const bounds. Returns null if the constructor is not eligible. * * @param array $types - * @param array $classTemplates + * @param array $classTemplates * * @return list|null */ @@ -1858,7 +2359,7 @@ public static function checkReturn(string $function, mixed $value, object|string * Checks whether a GenericTypeNode return contract is an exact identity self-return * (e.g. `@return self` or `@return static`) matching the class's declared template order. * - * @param array $classTemplates + * @param array $classTemplates */ private static function isIdentitySelfGenericReturn( GenericTypeNode $returnTypeNode, @@ -1967,7 +2468,7 @@ private static function executeSimpleReturnPlan( private static function compileSimpleReturnOp(TypeNode $resolvedType): array { $inner = $resolvedType; - while ($inner instanceof \PHPStan\PhpDocParser\Ast\Type\NullableTypeNode) { + while ($inner instanceof NullableTypeNode) { $inner = $inner->type; }