Skip to content

Commit 9ebfb43

Browse files
authored
Performance Improvements and Optimizations (#86)
* Refactor code style and improve performance in FunctionContractInjector, ScopeManager, and ObjectShapeValidator * Enhance ParamChecker and TemplateManager with 2D caching for improved performance and type symbol verification * Refactor caching mechanisms in SpecialTypeResolver and enhance ObjectShapeValidator with improved property checks * Refactor InlineChecker to implement 2D and 3D caching for resolved class contexts and null properties * Enhance caching mechanisms in InlineChecker and DocblockParser with 2D caching for improved performance and type resolution * Enhance ReturnChecker with 2D caching for substituted return types and improve generic iterable checks * Enhance GeneratorChecker and ConstValidator with improved caching mechanisms for yield/send types and wildcard constants * Update bug report template to include a default title and format placeholder URL * Remove security vulnerability reporting link from issue template
1 parent 1125f91 commit 9ebfb43

14 files changed

Lines changed: 446 additions & 214 deletions

‎.github/ISSUE_TEMPLATE/1-bug-report.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name: Bug report
22
description: If something isn't working as expected.
3-
title: ""
3+
title: "[Bug]: "
44
labels: ["bug"]
55
body:
66
- type: textarea
@@ -18,7 +18,7 @@ body:
1818
label: Code snippet that reproduces the problem
1919
description: |
2020
Please reproduce the issue with the [on-line TypePHP playground](https://typephp-php.github.io/docs/playground), get a unique URL with the Share button and post it here.
21-
placeholder: https://typephp-php.github.io/docs/playground#code=<unique_id>
21+
placeholder: "https://typephp-php.github.io/docs/playground#code=<unique_id>"
2222
validations:
2323
required: false
2424

‎.github/ISSUE_TEMPLATE/config.yml‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
blank_issues_enabled: false
22
contact_links:
3-
- name: Report a security vulnerability
4-
url: https://github.com/typephp-php/typephp/security/policy
5-
about: Please review our security policy for more details.
63
- name: Support question
74
url: https://github.com/typephp-php/typephp/discussions/new?category=q-a
85
about: Please open a new discussion instead. Thank you.

‎src/Internal/Ast/FunctionContractInjector.php‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_|
276276

277277
private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool
278278
{
279-
$visitor = new class() extends NodeVisitorAbstract {
279+
$visitor = new class () extends NodeVisitorAbstract {
280280
public bool $isGen = false;
281281

282282
public function enterNode(Node $n): ?int
@@ -678,8 +678,10 @@ public static function buildWrappedYieldNode(Node\Expr\Yield_ $n, Node\Expr $thi
678678
private static function wrapGeneratorReturns(array $stmts, Node\Expr $thisArg): array
679679
{
680680
$traverser = new NodeTraverser();
681-
$traverser->addVisitor(new class($thisArg) extends NodeVisitorAbstract {
682-
public function __construct(private Node\Expr $thisArg) {}
681+
$traverser->addVisitor(new class ($thisArg) extends NodeVisitorAbstract {
682+
public function __construct(private Node\Expr $thisArg)
683+
{
684+
}
683685

684686
public function enterNode(Node $n): int|Node|null
685687
{
@@ -738,7 +740,7 @@ private static function wrapNonGeneratorReturns(
738740
bool $hasSelfOut = false
739741
): array {
740742
$traverser = new NodeTraverser();
741-
$traverser->addVisitor(new class($thisArg, $isNativeVoid, $needsReturnVars, $hasReturn, $byRefParams, $hasSelfOut) extends NodeVisitorAbstract {
743+
$traverser->addVisitor(new class ($thisArg, $isNativeVoid, $needsReturnVars, $hasReturn, $byRefParams, $hasSelfOut) extends NodeVisitorAbstract {
742744
/**
743745
* @param array<string> $byRefParams
744746
*/
@@ -749,7 +751,8 @@ public function __construct(
749751
private bool $hasReturn,
750752
private array $byRefParams,
751753
private bool $hasSelfOut
752-
) {}
754+
) {
755+
}
753756

754757
public function enterNode(Node $n): int|array|null
755758
{

‎src/Internal/Ast/ScopeManager.php‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,36 +5,40 @@
55
namespace TypePHP\Internal\Ast;
66

77
use PhpParser\Node;
8-
use PHPStan\PhpDocParser\Parser\TokenIterator;
98
use TypePHP\Internal\Docblock\DocblockExtractor;
10-
use TypePHP\Internal\Docblock\DocblockNormalizer;
119

1210
/**
1311
* @internal Manages lexical scope stack frames and extracts local @var variable annotations.
1412
*/
1513
final class ScopeManager
1614
{
1715
/**
18-
* @var array<int, array<string, string>>
16+
* @var list<array<string, string>>
1917
*/
2018
private array $scopeStack = [[]];
2119

2220
/**
23-
* Pushes a new scope frame, inheriting variables from the parent scope.
21+
* Tracks the current scope frame depth.
22+
*/
23+
private int $depth = 0;
24+
25+
/**
26+
* Pushes a new empty lexical scope frame (O(1)).
2427
*/
2528
public function pushScope(): void
2629
{
27-
$currentScope = end($this->scopeStack);
28-
$this->scopeStack[] = $currentScope !== false ? $currentScope : [];
30+
$this->depth++;
31+
$this->scopeStack[] = [];
2932
}
3033

3134
/**
32-
* Pops the top scope frame, restoring variables back to the parent scope.
35+
* Pops the top scope frame, restoring the previous lexical scope (O(1)).
3336
*/
3437
public function popScope(): void
3538
{
36-
if (\count($this->scopeStack) > 1) {
39+
if ($this->depth > 0) {
3740
array_pop($this->scopeStack);
41+
$this->depth--;
3842
}
3943
}
4044

@@ -44,12 +48,12 @@ public function popScope(): void
4448
*/
4549
public function extractVarDocblock(string $docText, ?Node\Expr $expr = null): void
4650
{
47-
try {
48-
$docText = DocblockNormalizer::normalize($docText);
49-
[$phpDocParser, $lexer] = DocblockExtractor::getParserComponents();
51+
if (! str_contains($docText, 'var')) {
52+
return;
53+
}
5054

51-
$tokens = new TokenIterator($lexer->tokenize($docText));
52-
$phpDocNode = $phpDocParser->parse($tokens);
55+
try {
56+
$phpDocNode = DocblockExtractor::parseDocString($docText);
5357
$varTags = DocblockExtractor::getVarTags($phpDocNode);
5458

5559
foreach ($varTags as $varTag) {
@@ -63,18 +67,20 @@ public function extractVarDocblock(string $docText, ?Node\Expr $expr = null): vo
6367
}
6468

6569
if ($varName !== '') {
66-
$currentScopeIndex = \count($this->scopeStack) - 1;
67-
$this->scopeStack[$currentScopeIndex][$varName] = $typeString;
70+
$this->scopeStack[$this->depth][$varName] = $typeString;
6871
}
6972
}
7073
} catch (\Throwable $e) {
7174
// Silently ignore malformed docblocks
7275
}
7376
}
7477

78+
/**
79+
* Resolves a variable type by walking upward through the lexical scope chain.
80+
*/
7581
public function getVarTypeFromScope(string $varName): ?string
7682
{
77-
for ($i = \count($this->scopeStack) - 1; $i >= 0; $i--) {
83+
for ($i = $this->depth; $i >= 0; $i--) {
7884
if (isset($this->scopeStack[$i][$varName])) {
7985
return $this->scopeStack[$i][$varName];
8086
}

‎src/Internal/Checker/GeneratorChecker.php‎

Lines changed: 89 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,29 @@
1919
*/
2020
final class GeneratorChecker
2121
{
22+
/**
23+
* O(1) Fast-path cache for generators determined to have no return contracts.
24+
*
25+
* @var array<string, true>
26+
*/
27+
private static array $noContractCache = [];
28+
29+
/**
30+
* Cache for resolved yield & send types of static / non-generic generators:
31+
* [$function] => array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode}.
32+
*
33+
* @var array<string, array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode}>
34+
*/
35+
private static array $staticYieldTypeCache = [];
36+
37+
/**
38+
* 2D Cache for resolved yield & send types of generic generators:
39+
* [$function][$templateSignature] => array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode}.
40+
*
41+
* @var array<string, array<string, array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode}>>
42+
*/
43+
private static array $genericYieldTypeCache = [];
44+
2245
/**
2346
* Validates a value sent into a generator via $gen->send() against TSend.
2447
*/
@@ -32,12 +55,12 @@ public static function checkSend(
3255
return null;
3356
}
3457

35-
$returnTypeNode = self::resolveGeneratorReturnType($function, $thisOrClass);
36-
if (! ($returnTypeNode instanceof GenericTypeNode)) {
58+
$types = self::resolveYieldAndSendTypes($function, $thisOrClass);
59+
if ($types === null) {
3760
return $sendValue;
3861
}
3962

40-
$sendTypeNode = $returnTypeNode->genericTypes[2] ?? null;
63+
$sendTypeNode = $types[2];
4164
if ($sendTypeNode === null) {
4265
return $sendValue;
4366
}
@@ -48,7 +71,7 @@ public static function checkSend(
4871
}
4972

5073
/**
51-
* Validates yielded keys and values from a generator function against TKey and TValue.
74+
* Validates yielded keys and values from a generator function against TKey and TValue with zero-allocation caching.
5275
*/
5376
public static function checkYield(
5477
string $function,
@@ -57,12 +80,12 @@ public static function checkYield(
5780
TypeValidatorRegistry $registry,
5881
object|string|null $thisOrClass = null
5982
): mixed {
60-
$returnTypeNode = self::resolveGeneratorReturnType($function, $thisOrClass);
61-
if ($returnTypeNode === null) {
83+
$types = self::resolveYieldAndSendTypes($function, $thisOrClass);
84+
if ($types === null) {
6285
return $value;
6386
}
6487

65-
[$keyTypeNode, $itemTypeNode] = self::extractYieldTypes($returnTypeNode);
88+
[$keyTypeNode, $itemTypeNode] = $types;
6689

6790
if ($key !== null && $keyTypeNode !== null) {
6891
$err = $registry->validate($key, $keyTypeNode, "$function(): Return iterator key");
@@ -82,43 +105,91 @@ public static function checkYield(
82105
}
83106

84107
/**
85-
* Resolves the generator's return contract, applying alias expansion, template substitution, and special types.
108+
* Resolves and caches the generator's yielded key, value, and sent types in memory.
109+
*
110+
* @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode}|null
86111
*/
87-
private static function resolveGeneratorReturnType(string $function, object|string|null $thisOrClass): ?TypeNode
112+
private static function resolveYieldAndSendTypes(string $function, object|string|null $thisOrClass): ?array
88113
{
114+
if (isset(self::$noContractCache[$function])) {
115+
return null;
116+
}
117+
118+
if (isset(self::$staticYieldTypeCache[$function])) {
119+
return self::$staticYieldTypeCache[$function];
120+
}
121+
89122
$contract = DocblockParser::parse($function);
90123
$returnTypeNode = $contract['return'] ?? null;
91124

92125
if ($returnTypeNode === null) {
126+
self::$noContractCache[$function] = true;
127+
93128
return null;
94129
}
95130

131+
$allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])];
96132
$aliases = $contract['aliases'] ?? [];
133+
$hasGenerics = \count($allTemplates) > 0;
134+
$hasAliases = \count($aliases) > 0;
135+
$thisObj = \is_object($thisOrClass) ? $thisOrClass : null;
136+
137+
// Static / non-generic generator: cache permanently for this function
138+
if (! $hasGenerics && ! $hasAliases && $thisObj === null) {
139+
$resolvedNode = SpecialTypeResolver::resolve($returnTypeNode, $function, null);
140+
141+
return self::$staticYieldTypeCache[$function] = self::extractYieldTypes($resolvedNode);
142+
}
143+
144+
// Generic generator: check signature-based 2D cache
145+
$boundTemplates = $hasGenerics ? TemplateManager::getBoundTemplates($function, $thisObj, $allTemplates) : [];
146+
147+
$sig = null;
148+
$boundCount = \count($boundTemplates);
149+
if ($boundCount > 0 && $boundCount <= 2 && ! $hasAliases && $thisObj === null) {
150+
if ($boundCount === 1) {
151+
$first = reset($boundTemplates);
152+
$sig = $first instanceof IdentifierTypeNode ? $first->name : (string) $first;
153+
} else {
154+
$sig = '';
155+
foreach ($boundTemplates as $v) {
156+
$sig .= ($v instanceof IdentifierTypeNode ? $v->name : (string) $v) . '|';
157+
}
158+
}
159+
160+
if (isset(self::$genericYieldTypeCache[$function][$sig])) {
161+
return self::$genericYieldTypeCache[$function][$sig];
162+
}
163+
}
164+
97165
if ($returnTypeNode instanceof IdentifierTypeNode && isset($aliases[$returnTypeNode->name])) {
98166
$returnTypeNode = $aliases[$returnTypeNode->name];
99167
}
100168

101-
$thisObj = \is_object($thisOrClass) ? $thisOrClass : null;
102-
$allTemplates = [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])];
103-
$boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $allTemplates);
104-
105169
if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) {
106170
$returnTypeNode = TemplateSubstitutor::substitute($returnTypeNode, $boundTemplates, $allTemplates);
107171
$returnTypeNode = SpecialTypeResolver::resolve($returnTypeNode, $function, $thisObj);
108172
}
109173

110-
return $returnTypeNode;
174+
$types = self::extractYieldTypes($returnTypeNode);
175+
176+
if ($sig !== null) {
177+
self::$genericYieldTypeCache[$function][$sig] = $types;
178+
}
179+
180+
return $types;
111181
}
112182

113183
/**
114-
* Extracts yielded key and item TypeNodes from a resolved generator/array AST node.
184+
* Extracts yielded key, item, and sent (TSend) TypeNodes from a resolved generator/array AST node.
115185
*
116-
* @return array{0: ?TypeNode, 1: ?TypeNode}
186+
* @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode}
117187
*/
118188
private static function extractYieldTypes(TypeNode $returnTypeNode): array
119189
{
120190
$itemTypeNode = null;
121191
$keyTypeNode = null;
192+
$sendTypeNode = null;
122193

123194
if ($returnTypeNode instanceof GenericTypeNode) {
124195
$typesCount = \count($returnTypeNode->genericTypes);
@@ -127,11 +198,12 @@ private static function extractYieldTypes(TypeNode $returnTypeNode): array
127198
} elseif ($typesCount >= 2) {
128199
$keyTypeNode = $returnTypeNode->genericTypes[0];
129200
$itemTypeNode = $returnTypeNode->genericTypes[1];
201+
$sendTypeNode = $returnTypeNode->genericTypes[2] ?? null;
130202
}
131203
} elseif ($returnTypeNode instanceof ArrayTypeNode) {
132204
$itemTypeNode = $returnTypeNode->type;
133205
}
134206

135-
return [$keyTypeNode, $itemTypeNode];
207+
return [$keyTypeNode, $itemTypeNode, $sendTypeNode];
136208
}
137209
}

0 commit comments

Comments
 (0)