Skip to content

Commit 02b1861

Browse files
authored
Bug fixes and Performance Improvement... (#87)
* Refactor caches in HierarchyResolver, SpecialTypeResolver, IgnoreManager, and StubManager to use 2D arrays for improved organization and access patterns. * Enhance magic method and property handling with support for __get and __call, including parameter scope and return checks. Update configuration for granular control over magic property reads and writes. * Add caching for property template references and self-out method checks in InlineChecker; implement instance template binding restoration in TemplateManager; introduce tests for typestate transitions in FixtureTypestateAuthSession * Fix condition check in InlineChecker to ensure both 'object' and 'class' are set before comparison
1 parent 9ebfb43 commit 02b1861

16 files changed

Lines changed: 825 additions & 163 deletions

‎src/Internal/Ast/FunctionContractInjector.php‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,15 @@ public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?
4949
$methodName = $isClassMethod ? strtolower($node->name->toString()) : '';
5050
$isConstructor = $isClassMethod && $methodName === '__construct';
5151
$isMagicLifecycle = $isClassMethod && \in_array($methodName, ['__construct', '__destruct', '__clone'], true);
52+
$isMagicGet = $isClassMethod && $methodName === '__get';
53+
$isMagicCall = $isClassMethod && ($methodName === '__call' || $methodName === '__callstatic');
5254
$isNativeNever = $node->returnType instanceof Node\Identifier && strtolower($node->returnType->name) === 'never';
5355
$isNativeVoid = $node->returnType instanceof Node\Identifier && strtolower($node->returnType->name) === 'void';
5456
$isPrivate = $isClassMethod && $node->isPrivate();
5557

5658
$paramCount = \count($node->params);
5759

58-
$hasParam = self::hasParamContracts(
60+
$hasParam = ($isMagicGet || $isMagicCall) || self::hasParamContracts(
5961
$docText,
6062
$isClassMethod,
6163
$hasInheritance,
@@ -90,20 +92,20 @@ public static function inject(Node\Stmt\Function_|Node\Stmt\ClassMethod $node, ?
9092
$hasReturn = ! $isMagicLifecycle
9193
&& ! $isNativeNever
9294
&& ! ($isNativeVoid && ! $hasReturnDoc)
93-
&& self::hasReturnContracts($docText, $isClassMethod, $isPrivate);
95+
&& ($isMagicGet || $isMagicCall || self::hasReturnContracts($docText, $isClassMethod, $isPrivate));
9496

9597
if (! $hasParam && ! $hasReturn && ! $hasParamOut && ! $hasSelfOut) {
9698
return;
9799
}
98100

99101
$thisArg = self::resolveThisArg($isClassMethod, $node);
100-
$needsReturnVars = $hasParam && ($paramCount > 0) && (
102+
$needsReturnVars = ($hasParam && ($paramCount > 0) && (
101103
$hasInheritance || str_contains($docText, ' is ') || ($hasReturnDoc && str_contains($docText, '$'))
102-
);
104+
)) || ($isClassMethod && $paramCount > 0 && ($isMagicGet || $isMagicCall));
103105

104106
$injectedStmts = [];
105107
if ($hasParam) {
106-
$injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg, $isReadonlyClass);
108+
$injectedStmts = self::buildParamInjections($node->params, $docText, $thisArg, $isReadonlyClass, $needsReturnVars);
107109
}
108110

109111
if ($hasReturn || $hasParamOut || $hasSelfOut) {
@@ -313,9 +315,10 @@ private static function buildParamInjections(
313315
array $params,
314316
string $docText,
315317
Node\Expr $thisArg,
316-
bool $isReadonlyClass = false
318+
bool $isReadonlyClass = false,
319+
bool $needsReturnVars = false
317320
): array {
318-
$injectedStmts = [self::buildSetupScopeStmt($params, $thisArg)];
321+
$injectedStmts = [self::buildSetupScopeStmt($params, $thisArg, $needsReturnVars)];
319322
$callableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isCallableCandidate'], 'wrapCallable', $isReadonlyClass);
320323
$iterableWrappers = self::buildParamWrappers($params, $docText, $thisArg, [self::class, 'isIterableCandidate'], 'wrapIterable', $isReadonlyClass);
321324

@@ -325,7 +328,7 @@ private static function buildParamInjections(
325328
/**
326329
* @param array<Node\Param> $params
327330
*/
328-
private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg): Node\Stmt\If_
331+
private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, bool $needsReturnVars = false): Node\Stmt\If_
329332
{
330333
$arrayItems = [];
331334
foreach ($params as $param) {
@@ -389,6 +392,35 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg):
389392

390393
$combinedCondition = new Node\Expr\BinaryOp\BooleanOr($noParamCacheCheck, $hasTemplatesCheck);
391394

395+
if ($needsReturnVars) {
396+
$ifStmt = new Node\Stmt\If_(
397+
new Node\Expr\ConstFetch(new Node\Name('true')),
398+
[
399+
'stmts' => [
400+
$argsAssign,
401+
new Node\Stmt\If_(
402+
$combinedCondition,
403+
[
404+
'stmts' => [
405+
new Node\Stmt\If_(
406+
new Node\Expr\Instanceof_(
407+
new Node\Expr\Assign(new Node\Expr\Variable('__typephpErr'), $checkCall),
408+
new Node\Name\FullyQualified('TypePHP\Internal\Diagnostic\ErrorMessage')
409+
),
410+
['stmts' => [$throwStmt]]
411+
),
412+
],
413+
]
414+
),
415+
],
416+
]
417+
);
418+
419+
$ifStmt->setAttribute('typephp_injected', true);
420+
421+
return $ifStmt;
422+
}
423+
392424
$ifStmt = new Node\Stmt\If_(
393425
$combinedCondition,
394426
[

‎src/Internal/Checker/InlineChecker.php‎

Lines changed: 169 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,22 @@ final class InlineChecker
6161
*/
6262
public static array $nullPropertyCache = [];
6363

64+
/**
65+
* Cache for whether a class property's type references generic templates:
66+
* [$className][$propName] => bool.
67+
*
68+
* @var array<string, array<string, bool>>
69+
*/
70+
private static array $propertyUsesTemplatesCache = [];
71+
72+
/**
73+
* Cache for whether a class has any methods declaring @self-out or @this-out:
74+
* [$className] => bool.
75+
*
76+
* @var array<string, bool>
77+
*/
78+
private static array $classHasSelfOutCache = [];
79+
6480
/**
6581
* Resets internal type node and function caches. Useful for test isolation.
6682
*/
@@ -69,6 +85,8 @@ public static function reset(): void
6985
self::$parsedTypeNodeCache = [];
7086
self::$resolvedClassContextCache = [];
7187
self::$nullPropertyCache = [];
88+
self::$propertyUsesTemplatesCache = [];
89+
self::$classHasSelfOutCache = [];
7290
}
7391

7492
/**
@@ -236,24 +254,39 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string
236254
return $value;
237255
}
238256

239-
$typeNode = DocblockParser::parseProperty($className, $propName);
240-
if ($typeNode === null) {
257+
$rawTypeNode = DocblockParser::parseProperty($className, $propName);
258+
if ($rawTypeNode === null) {
241259
self::$nullPropertyCache[$className][$propName] = true;
242260

243261
return $value;
244262
}
245263

246-
if (! self::shouldValidateType($typeNode)) {
264+
if (! self::shouldValidateType($rawTypeNode)) {
247265
return $value;
248266
}
249267

268+
$propertyUsesTemplates = false;
269+
$typeNode = $rawTypeNode;
270+
250271
if (\is_object($objectOrClass)) {
251-
$typeNode = self::substitutePropertyGenerics($typeNode, $objectOrClass, $className);
272+
$propertyUsesTemplates = self::propertyUsesTemplates($rawTypeNode, $className, $propName);
273+
if ($propertyUsesTemplates) {
274+
$typeNode = self::substitutePropertyGenerics($rawTypeNode, $objectOrClass, $className);
275+
}
252276
}
253277

254278
try {
255279
$err = $registry->validate($value, $typeNode, 'Property ' . $className . '::$' . $propName);
256280
if ($err !== null) {
281+
if (
282+
$propertyUsesTemplates &&
283+
\is_object($objectOrClass) &&
284+
self::classHasSelfOut($className) &&
285+
self::trySelfOutTransition($value, $objectOrClass, $propName, $registry)
286+
) {
287+
return $value;
288+
}
289+
257290
return $err;
258291
}
259292
} catch (\Throwable $e) {
@@ -263,6 +296,138 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string
263296
return $value;
264297
}
265298

299+
/**
300+
* Checks if a property's declared type references class generic templates with memoization.
301+
*/
302+
private static function propertyUsesTemplates(TypeNode $rawTypeNode, string $className, string $propName): bool
303+
{
304+
if (isset(self::$propertyUsesTemplatesCache[$className][$propName])) {
305+
return self::$propertyUsesTemplatesCache[$className][$propName];
306+
}
307+
308+
$constructorTarget = $className . '::__construct';
309+
$contract = DocblockParser::parse($constructorTarget);
310+
$allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])];
311+
312+
if ($allTemplates === []) {
313+
return self::$propertyUsesTemplatesCache[$className][$propName] = false;
314+
}
315+
316+
return self::$propertyUsesTemplatesCache[$className][$propName] = DocblockParser::typeReferencesTemplate($rawTypeNode, $allTemplates);
317+
}
318+
319+
/**
320+
* Checks if a class declares any methods containing @self-out or @this-out annotations with memoization.
321+
*/
322+
private static function classHasSelfOut(string $className): bool
323+
{
324+
if (isset(self::$classHasSelfOutCache[$className])) {
325+
return self::$classHasSelfOutCache[$className];
326+
}
327+
328+
if (! class_exists($className) && ! trait_exists($className) && ! interface_exists($className)) {
329+
return self::$classHasSelfOutCache[$className] = false;
330+
}
331+
332+
try {
333+
/** @var class-string<object> $className */
334+
$ref = new \ReflectionClass($className);
335+
foreach ($ref->getMethods() as $method) {
336+
$doc = $method->getDocComment();
337+
if ($doc !== false && (str_contains($doc, 'self-out') || str_contains($doc, 'this-out'))) {
338+
return self::$classHasSelfOutCache[$className] = true;
339+
}
340+
}
341+
} catch (\Throwable $e) {
342+
// Silently ignore reflection errors
343+
}
344+
345+
return self::$classHasSelfOutCache[$className] = false;
346+
}
347+
348+
/**
349+
* Attempts a typestate transition when a property assignment to $this fails against current bindings.
350+
*/
351+
private static function trySelfOutTransition(mixed $value, object $object, string $propName, TypeValidatorRegistry $registry): bool
352+
{
353+
if (! Config::isSelfOutEnabled()) {
354+
return false;
355+
}
356+
357+
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 7);
358+
$callerFrame = null;
359+
$callerFunction = null;
360+
$contract = null;
361+
362+
foreach ($trace as $frame) {
363+
if (isset($frame['object'], $frame['class']) && $frame['object'] === $object) {
364+
if ($frame['class'] === 'TypePHP\Internal\RuntimeTypeChecker' || str_starts_with($frame['class'], 'TypePHP\\Internal\\')) {
365+
continue;
366+
}
367+
368+
$candidateFunction = $frame['class'] . '::' . $frame['function'];
369+
$candidateContract = DocblockParser::parse($candidateFunction);
370+
371+
if (($candidateContract['hasSelfOutContract'] ?? false) && $candidateContract['selfOut'] !== null) {
372+
$callerFrame = $frame;
373+
$callerFunction = $candidateFunction;
374+
$contract = $candidateContract;
375+
376+
break;
377+
}
378+
}
379+
}
380+
381+
if ($callerFrame === null || $callerFunction === null || $contract === null) {
382+
return false;
383+
}
384+
385+
$selfOutNode = $contract['selfOut'];
386+
$allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])];
387+
$boundTemplates = (\count($allTemplates) > 0)
388+
? TemplateManager::getBoundTemplates($callerFunction, $object, $allTemplates)
389+
: [];
390+
391+
if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) {
392+
$selfOutNode = TemplateSubstitutor::substitute($selfOutNode, $boundTemplates, $allTemplates);
393+
$selfOutNode = SpecialTypeResolver::resolve($selfOutNode, $callerFunction, $object);
394+
}
395+
396+
$vars = $callerFrame['args'] ?? [];
397+
if (
398+
$selfOutNode instanceof ConditionalTypeForParameterNode ||
399+
$selfOutNode instanceof ConditionalTypeNode
400+
) {
401+
$selfOutNode = ConditionalChecker::resolve($selfOutNode, $vars, $boundTemplates, $registry, $callerFunction);
402+
}
403+
404+
if (! ($selfOutNode instanceof GenericTypeNode)) {
405+
return false;
406+
}
407+
408+
$previousBindings = TemplateManager::getBoundTemplatesForInstance($object);
409+
410+
TemplateManager::bindInstanceFromNode($object, $selfOutNode, forceBind: true);
411+
412+
$className = $object::class;
413+
$propTypeNode = DocblockParser::parseProperty($className, $propName);
414+
if ($propTypeNode !== null) {
415+
$propTypeNode = self::substitutePropertyGenerics($propTypeNode, $object, $className);
416+
}
417+
418+
$testErr = $propTypeNode !== null
419+
? $registry->validate($value, $propTypeNode, 'Property ' . $className . '::$' . $propName)
420+
: null;
421+
422+
if ($testErr === null) {
423+
return true;
424+
}
425+
426+
TemplateManager::restoreInstanceBindings($object, $previousBindings);
427+
428+
return false;
429+
}
430+
266431
/**
267432
* Resolves caller class or function context and applies templates & type aliases to the AST.
268433
*/

‎src/Internal/Checker/ParamChecker.php‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ public static function reset(): void
104104
*/
105105
public static function areAllParamsUnconstrained(string $effectiveFunction): bool
106106
{
107-
if (str_contains($effectiveFunction, '__call')) {
107+
if (str_contains($effectiveFunction, '__call') || str_ends_with($effectiveFunction, '::__get')) {
108108
return false;
109109
}
110110

@@ -149,20 +149,21 @@ public static function checkParams(
149149
}
150150

151151
$isMagicCall = str_ends_with($effectiveFunction, '::__call') || str_ends_with($effectiveFunction, '::__callStatic');
152+
$isMagicGet = str_ends_with($effectiveFunction, '::__get');
152153

153-
if (! $isMagicCall && isset(self::$noParamContractCache[$effectiveFunction])) {
154+
if (! $isMagicCall && ! $isMagicGet && isset(self::$noParamContractCache[$effectiveFunction])) {
154155
return null;
155156
}
156157

157-
if ($vars === [] && ! $isMagicCall) {
158+
if ($vars === [] && ! $isMagicCall && ! $isMagicGet) {
158159
return null;
159160
}
160161

161162
$magicError = self::handleMagicCall($effectiveFunction, $vars, $thisObj, $registry);
162163
if ($magicError !== null) {
163164
return $magicError;
164165
}
165-
if ($isMagicCall) {
166+
if ($isMagicCall || $isMagicGet) {
166167
return null;
167168
}
168169

0 commit comments

Comments
 (0)