Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
248b811
Introduce targeted optimization for bottlenecks found via profiler
rcalicdan Nov 17, 2026
5b41093
Optimized ArrayShapeValidator
rcalicdan Nov 17, 2026
e196d93
Enhance RuntimeTypeChecker and ParamChecker with new configuration op…
rcalicdan Nov 17, 2026
8901e44
Add /benchmark/ directory to .gitignore
rcalicdan Nov 17, 2026
055913e
Enhance type evaluation by adding trusted variable types to evaluator…
rcalicdan Nov 17, 2026
f2259db
Add fast-path handling for common scalar identifiers in ParamChecker …
rcalicdan Nov 17, 2026
61eb228
Enhance RuntimeTypeChecker with additional parameter check constants …
rcalicdan Nov 17, 2026
06c6fcf
Refactor MemberAssignChecker and RuntimeTypeChecker for improved type…
rcalicdan Nov 18, 2026
1206063
Enhance MemberAssignChecker with improved contract validation and gen…
rcalicdan Nov 19, 2026
06f28b0
Refactor type substitution and resolution in TemplateSubstitutor and …
rcalicdan Nov 19, 2026
5302c47
Enhance type checking and caching mechanisms in ConditionalChecker, G…
rcalicdan Nov 19, 2026
dead388
Massively improve performance in Various internal components
rcalicdan Nov 19, 2026
a065c80
Enhance type annotations across various components for improved type …
rcalicdan Nov 19, 2026
e05456c
Enhance TemplateManager with additional caching mechanisms for generi…
rcalicdan Nov 19, 2026
62f06c5
Enhance ContractVisitor and EliminationSafetyPolicy to support traits…
rcalicdan Nov 19, 2026
6e867c9
Enhance ParamChecker and TemplateManager with improved type handling …
rcalicdan Nov 20, 2026
a4b97a5
Enhance ParamChecker, ReturnChecker, TemplateManager, RuntimeTypeChec…
rcalicdan Nov 21, 2026
3a656c6
Refactor type validation logic and enhance class-string handling
rcalicdan Nov 22, 2026
f92b2a3
Enhance ContractVisitor and NodeBuilder to support class constant che…
rcalicdan Nov 22, 2026
b535186
Refactor ParamChecker and TemplateManager by improving template bindi…
rcalicdan Nov 22, 2026
781422b
Add tests for cross-namespace imported type alias resolution and rela…
rcalicdan Nov 22, 2026
60b490b
Refactor CRLF line-drift test to update parameter type from non-empty…
rcalicdan Nov 22, 2026
48e8836
Enhance SpecialTypeResolver to support autoload parameter in type res…
rcalicdan Nov 22, 2026
4bf9100
Refactor CollectionElementValidator and GenericValidator to streamlin…
rcalicdan Nov 22, 2026
fd779e9
Refactor RuntimeTypeChecker to enhance type validation logic and impr…
rcalicdan Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ benchmark.php
.php-cs-fixer.cache
/app
/coverage-report
/coverage
/coverage
/benchmark/
73 changes: 63 additions & 10 deletions src/Internal/Ast/ContractVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ final class ContractVisitor extends NodeVisitorAbstract
private string $currentNamespace = '';

/**
* @var list<array{name: ?string, isAnonymous: bool, hasInheritance: bool, hasPropertyWithDoc: bool, isReadonly: bool, isFinal: bool, hasTemplates: bool}>
* @var list<array{name: ?string, isAnonymous: bool, hasInheritance: bool, hasRealInheritance: bool, hasPropertyWithDoc: bool, isReadonly: bool, isFinal: bool, hasTemplates: bool, isTrait?: bool}>
*/
private array $classStack = [];

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -904,6 +909,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)) {
Expand Down Expand Up @@ -975,6 +981,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_)) {
Expand Down Expand Up @@ -1036,6 +1045,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
'isReadonly' => $isReadonly,
'isFinal' => $isFinal,
'hasTemplates' => $hasTemplates,
'isTrait' => $isTrait,
];
}

Expand Down Expand Up @@ -1463,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));
Expand All @@ -1471,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
Expand Down Expand Up @@ -1899,6 +1943,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);

Expand Down
10 changes: 9 additions & 1 deletion src/Internal/Ast/Elimination/EliminationSafetyPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ final class EliminationSafetyPolicy
* and scalar generics (int<min, max>, 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.
*
Expand Down Expand Up @@ -91,6 +91,10 @@ public static function isReturnEliminationSafe(
return true;
}

if ($classContext['isTrait'] ?? false) {
return false;
}

$hasRealInheritance = $classContext['hasRealInheritance'] ?? true;
if (! $hasRealInheritance) {
return true;
Expand Down Expand Up @@ -139,6 +143,10 @@ public static function isGeneratorEliminationSafe(
return true;
}

if ($classContext['isTrait'] ?? false) {
return false;
}

$hasRealInheritance = $classContext['hasRealInheritance'] ?? true;
if (! $hasRealInheritance) {
return true;
Expand Down
96 changes: 53 additions & 43 deletions src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>, non-empty-list<T>, T[]) verify keys are 0..n-1 and all values satisfy T.
* 4. Typed key-value maps (array<K, V>) 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<string, TypeNode> $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) {
Expand All @@ -72,24 +71,22 @@ 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;
}

/**
* 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
{
Expand Down Expand Up @@ -135,48 +132,54 @@ private static function satisfiesIdentifierArray(Array_ $arrayExpr, IdentifierTy
}

/**
* Evaluates an array expression against generic array containers:
* - Single template argument: list<T>, non-empty-list<T>, array<T>
* - Double template argument: array<K, V>, non-empty-array<K, V>
* @param array<string, TypeNode> $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<string, TypeNode> $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;
Expand All @@ -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;
}
}
Expand All @@ -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<string, TypeNode> $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;
Expand All @@ -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;
}
}
Expand All @@ -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<string, TypeNode> $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;
}
Expand Down Expand Up @@ -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;
}
}
Expand All @@ -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;
}
}
Expand Down
Loading
Loading