Skip to content

Commit 72e4979

Browse files
authored
Several Bug and edge cases resolve found in running noctud/collection (#133)
* Enhance type inference and validation in ParamChecker, TemplateManager, and RuntimeTypeChecker; add tests for iterable object handling and ignore tag support in callables Find in noctud collection report.. * Enhance ParamChecker and TemplateManager with improved type inference; add UnboundGeneratorTemplateTest for verifying template behavior in generators * Add ConditionalReturnGenericsTest for filterNotNull and flatten behaviors in generic collections * Add GenericMapFixture and tests for factory reconstruction variance in generics * Refactor TemplateManager to simplify type matching logic and add UnionBoundSpecializationTest for lazy closure template inference * Improve type annotations and formatting in various tests and TemplateManager for better clarity and consistency * Refactor ParamChecker to simplify traversable type resolution; add SpuriousTemplateBleedTest for verifying template behavior in generic collections * Enhance ParamChecker to utilize class templates in type substitution for improved generic handling * Enhance ParamChecker to support class alias substitution in traversable type resolution; add tests for aliased generics handling * Enhance ParamChecker to support class templates in template inference; add tests for generic map construction and inference * Enhance FunctionContractInjector and RuntimeTypeChecker to support scope management; add ScopeCleaner for template binding; introduce GenericStreamPipeline with tests for generator interleaving and template isolation * Fix formatting in FunctionContractInjector by adding spaces in anonymous class definitions for improved readability * Enhance ParamChecker to support ObjectShapeNode in template inference; add TuplePairStore with tests for heterogeneous key unification and template upper bounds enforcement * Add tests for cloned store template widening in immutable collections and maps * Refactor ParamChecker to improve return type handling and add NullableClosureAndTemplateDefaultInference tests for enhanced type inference * Enhance template inference by adding generator support in ParamChecker and TemplateManager; improve test coverage for nullable closures and template defaults * Refactor TemplateManager to utilize WeakMap for instance template bindings; add SelfPreserving subtype variance tests for enhanced type safety in generics * Enhance ParamChecker and TemplateManager with improved call binding handling; add propagation logic for instance properties and introduce LazyProxy and ClonedStore tests for type inference validation * Enhance propagateBindingsToInstanceProperties method to prevent premature initialization of uninitialized lazy objects; improve property inspection logic for better handling of lazy properties. * Implement generics for map and set structures, including immutable and mutable hash maps, with comprehensive type checking and tests for entries and keys views. Add Noctud-style entries view tests to ensure type consistency after accessing values. * Add caching for generic object contexts and template variances in ParamChecker and TemplateManager * Fix formatting by adding missing newlines in ParamChecker and TemplateManager * Fix PHP version check placement in ReturnGenericReificationTest * Add generic iterable and animal producer classes with tests for type inference across namespaces * Refactor contract cache handling in checkers and enhance method hierarchy resolution with dynamic class name support * Enhance ConstantAndEnumEvaluator with enum support and add comprehensive soundness tests * Refactor ArrayLiteralEvaluator to improve non-empty array and list checks, and add hasConcreteItem method for better item validation. Introduce ArrayLiteralSpreadSoundnessTest for comprehensive spread expression testing. * Refactor DocblockNormalizer to quote unquoted class constant keys in array/object shapes for phpdoc-parser compatibility. Add tests for conditional class constants and enums in various scenarios. * Enhance ContractVisitor with side-effect detection and hoisting for impure targets. Add tests for foreach and by-reference array item write contexts, ensuring proper handling of static properties and contract violations. * Enhance ContractVisitor and TemplateManager with improved generic type handling and add Nullable and Union Generic Pre-binding tests * Enhance InlineChecker and SpecialTypeResolver with namespace extraction and improved file metadata handling; add MultiNamespaceAndEnumTraitMetadataTest for comprehensive coverage of multi-namespace and trait use cases. * Refactor FunctionContractInjector to simplify return statement checks; add UnannotatedNativeReturnInjectionTest for verifying native return type injection behavior in standalone classes. * Add active call order tracking to TemplateManager and implement tests for re-entrant call stack behavior * Enhance DocblockNormalizer to support nested angle brackets and callable generics; add comprehensive tests for preservation and normalization of complex types. * fix code styling * Enhance ReportCommand output to include detailed report file information and summary statistics for violations and affected files. * Fix missing newline at end of file in ReportCommand.php
1 parent 66f5f2f commit 72e4979

64 files changed

Lines changed: 9419 additions & 448 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 283 additions & 35 deletions
Large diffs are not rendered by default.

‎src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,8 @@ private static function satisfiesIdentifierArray(Array_ $arrayExpr, IdentifierTy
128128
return match ($name) {
129129
'array', 'iterable', 'mixed' => true,
130130
'list' => self::isSequentialList($arrayExpr),
131-
'non-empty-array' => \count($arrayExpr->items) > 0,
132-
'non-empty-list' => \count($arrayExpr->items) > 0 && self::isSequentialList($arrayExpr),
131+
'non-empty-array' => self::hasConcreteItem($arrayExpr),
132+
'non-empty-list' => self::hasConcreteItem($arrayExpr) && self::isSequentialList($arrayExpr),
133133
default => false,
134134
};
135135
}
@@ -184,7 +184,7 @@ private static function satisfiesList(Array_ $arrayExpr, TypeNode $itemType, boo
184184

185185
$expectedIdx = 0;
186186
foreach ($arrayExpr->items as $item) {
187-
if ($item === null) {
187+
if ($item === null || $item->unpack) {
188188
return false;
189189
}
190190

@@ -216,7 +216,7 @@ private static function satisfiesKeyValueArray(Array_ $arrayExpr, TypeNode $keyT
216216

217217
$currentIdx = 0;
218218
foreach ($arrayExpr->items as $item) {
219-
if ($item === null) {
219+
if ($item === null || $item->unpack) {
220220
return false;
221221
}
222222

@@ -276,7 +276,7 @@ private static function satisfiesArrayShape(Array_ $arrayExpr, ArrayShapeNode $s
276276
$actualItems = [];
277277
$currentIdx = 0;
278278
foreach ($arrayExpr->items as $item) {
279-
if ($item === null) {
279+
if ($item === null || $item->unpack) {
280280
return false;
281281
}
282282

@@ -342,7 +342,7 @@ private static function isSequentialList(Array_ $arrayExpr): bool
342342
{
343343
$expectedIdx = 0;
344344
foreach ($arrayExpr->items as $item) {
345-
if ($item === null) {
345+
if ($item === null || $item->unpack) {
346346
return false;
347347
}
348348

@@ -356,4 +356,18 @@ private static function isSequentialList(Array_ $arrayExpr): bool
356356

357357
return true;
358358
}
359+
360+
/**
361+
* Checks whether an array expression contains at least one non-unpacked concrete item.
362+
*/
363+
private static function hasConcreteItem(Array_ $arrayExpr): bool
364+
{
365+
foreach ($arrayExpr->items as $item) {
366+
if ($item !== null && ! $item->unpack) {
367+
return true;
368+
}
369+
}
370+
371+
return false;
372+
}
359373
}

‎src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php‎

Lines changed: 118 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace TypePHP\Internal\Ast\Elimination\Evaluator;
66

7+
use BackedEnum;
78
use PhpParser\Node\Expr;
89
use PhpParser\Node\Expr\BinaryOp\BitwiseOr;
910
use PhpParser\Node\Expr\ClassConstFetch;
@@ -16,6 +17,7 @@
1617
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
1718
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
1819
use TypePHP\Internal\Resolver\SpecialTypeResolver;
20+
use UnitEnum;
1921

2022
/**
2123
* Statically evaluates whether constant fetches, enum cases, bitmasks,
@@ -25,13 +27,25 @@
2527
*/
2628
final class ConstantAndEnumEvaluator
2729
{
30+
/**
31+
* O(1) hash map of relative class keywords.
32+
*
33+
* @var array<string, true>
34+
*/
35+
private const RELATIVE_CLASS_KEYWORDS = [
36+
'self' => true,
37+
'static' => true,
38+
'parent' => true,
39+
'$this' => true,
40+
];
41+
2842
/**
2943
* Determines whether an expression satisfies constant or enum contracts.
3044
*
3145
* Flow of logic:
32-
* 1. Evaluates ClassConstFetch nodes against exact constants, wildcards, and base enum types.
46+
* 1. Evaluates ClassConstFetch nodes against exact constants, wildcards, and loaded enum cases.
3347
* 2. Evaluates bitwise OR expressions (A | B) against `int-mask-of` wildcards.
34-
* 3. Evaluates enum backing property reads (Enum::Case->value) against `value-of<Enum>`.
48+
* 3. Evaluates backed enum property reads (Enum::Case->value) against `value-of<Enum>`.
3549
*/
3650
public static function satisfies(Expr $expr, TypeNode $typeNode, string $currentFile = ''): bool
3751
{
@@ -60,9 +74,17 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty
6074
}
6175

6276
$constName = $fetch->name->toString();
77+
if (strtolower($constName) === 'class') {
78+
return false;
79+
}
80+
6381
$targetClassName = $fetch->class->toString();
6482

6583
if ($typeNode instanceof ConstTypeNode && $typeNode->constExpr instanceof ConstFetchNode) {
84+
if (! self::classesMatch($targetClassName, $typeNode->constExpr->className, $currentFile)) {
85+
return false;
86+
}
87+
6688
$docConstName = $typeNode->constExpr->name;
6789

6890
if (str_contains($docConstName, '*')) {
@@ -73,20 +95,31 @@ private static function satisfiesClassConst(ClassConstFetch $fetch, TypeNode $ty
7395
}
7496

7597
if ($typeNode instanceof IdentifierTypeNode) {
76-
if ($currentFile !== '') {
77-
$resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($targetClassName, $currentFile, false);
78-
$resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($typeNode->name, $currentFile, false);
98+
if (! self::classesMatch($targetClassName, $typeNode->name, $currentFile)) {
99+
return false;
100+
}
79101

80-
return $resolvedFetchClass !== '' && $resolvedFetchClass === $resolvedTypeClass;
102+
$resolvedEnum = self::resolveClassForReflection($targetClassName, $currentFile);
103+
if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false)) {
104+
return false;
81105
}
82106

83-
return $targetClassName === $typeNode->name;
107+
return self::isEnumCase($resolvedEnum, $constName);
84108
}
85109

86110
if ($typeNode instanceof GenericTypeNode && strtolower((string) $typeNode->type) === 'int-mask-of') {
87111
$inner = $typeNode->genericTypes[0] ?? null;
88112
if ($inner instanceof ConstTypeNode && $inner->constExpr instanceof ConstFetchNode) {
89-
return self::matchesWildcard($constName, $inner->constExpr->name);
113+
if (! self::classesMatch($targetClassName, $inner->constExpr->className, $currentFile)) {
114+
return false;
115+
}
116+
117+
$pattern = $inner->constExpr->name;
118+
if (str_contains($pattern, '*')) {
119+
return self::matchesWildcard($constName, $pattern);
120+
}
121+
122+
return $constName === $pattern;
90123
}
91124
}
92125

@@ -107,15 +140,15 @@ private static function satisfiesBitwiseOr(BitwiseOr $expr, TypeNode $typeNode,
107140
}
108141

109142
/**
110-
* Verifies whether an Enum::Case->value property access satisfies `value-of<Enum>`.
143+
* Verifies whether a BackedEnum::Case->value property access satisfies `value-of<Enum>`.
111144
*/
112145
private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode $typeNode, string $currentFile): bool
113146
{
114147
if (! ($fetch->name instanceof Identifier) || $fetch->name->name !== 'value') {
115148
return false;
116149
}
117150

118-
if (! ($fetch->var instanceof ClassConstFetch) || ! ($fetch->var->class instanceof Name)) {
151+
if (! ($fetch->var instanceof ClassConstFetch) || ! ($fetch->var->class instanceof Name) || ! ($fetch->var->name instanceof Identifier)) {
119152
return false;
120153
}
121154

@@ -129,15 +162,86 @@ private static function satisfiesEnumBackingValue(PropertyFetch $fetch, TypeNode
129162
}
130163

131164
$enumClassName = $fetch->var->class->toString();
165+
$caseName = $fetch->var->name->toString();
166+
167+
if (strtolower($caseName) === 'class') {
168+
return false;
169+
}
170+
171+
if (! self::classesMatch($enumClassName, $enumTarget->name, $currentFile)) {
172+
return false;
173+
}
174+
175+
$resolvedEnum = self::resolveClassForReflection($enumClassName, $currentFile);
176+
if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false) || ! is_subclass_of($resolvedEnum, BackedEnum::class)) {
177+
return false;
178+
}
179+
180+
return self::isEnumCase($resolvedEnum, $caseName);
181+
}
182+
183+
/**
184+
* Verifies whether two class references deterministically denote the same class/enum.
185+
*/
186+
private static function classesMatch(string $fetchClass, string $docClass, string $currentFile): bool
187+
{
188+
if ($docClass === '') {
189+
return false;
190+
}
191+
192+
$lowerFetch = strtolower($fetchClass);
193+
$lowerDoc = strtolower($docClass);
194+
195+
if ($lowerFetch === 'self' && $lowerDoc === 'self') {
196+
return true;
197+
}
198+
199+
if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerFetch]) || isset(self::RELATIVE_CLASS_KEYWORDS[$lowerDoc])) {
200+
return false;
201+
}
202+
203+
if ($fetchClass === $docClass) {
204+
return true;
205+
}
132206

133207
if ($currentFile !== '') {
134-
$resolvedEnumClass = SpecialTypeResolver::resolveFqcnForFile($enumClassName, $currentFile, false);
135-
$resolvedTargetClass = SpecialTypeResolver::resolveFqcnForFile($enumTarget->name, $currentFile, false);
208+
$resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($fetchClass, $currentFile, false);
209+
$resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($docClass, $currentFile, false);
136210

137-
return $resolvedEnumClass !== '' && $resolvedEnumClass === $resolvedTargetClass;
211+
return $resolvedFetchClass !== '' && $resolvedFetchClass === $resolvedTypeClass;
138212
}
139213

140-
return $enumClassName === $enumTarget->name;
214+
return false;
215+
}
216+
217+
/**
218+
* Resolves a class name without invoking autoloading.
219+
*/
220+
private static function resolveClassForReflection(string $rawClass, string $currentFile): string
221+
{
222+
if ($currentFile !== '') {
223+
return SpecialTypeResolver::resolveFqcnForFile($rawClass, $currentFile, false);
224+
}
225+
226+
return ltrim($rawClass, '\\');
227+
}
228+
229+
/**
230+
* Verifies that a symbol is a declared enum case (excluding regular class constants on enums).
231+
*/
232+
private static function isEnumCase(string $enumClass, string $caseName): bool
233+
{
234+
if (! enum_exists($enumClass, false) || ! is_subclass_of($enumClass, UnitEnum::class)) {
235+
return false;
236+
}
237+
238+
foreach ($enumClass::cases() as $case) {
239+
if ($case->name === $caseName) {
240+
return true;
241+
}
242+
}
243+
244+
return false;
141245
}
142246

143247
/**

0 commit comments

Comments
 (0)