Skip to content
Merged
Changes from all commits
Commits
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
41 changes: 39 additions & 2 deletions src/Analyser/LazyInternalScopeFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use PHPStan\Rules\Properties\PropertyReflectionFinder;
use PHPStan\Type\ClosureType;
use PHPStan\Type\ExpressionTypeResolverExtension;
use WeakReference;

#[GenerateFactory(interface: InternalScopeFactoryFactory::class, resultType: LazyInternalScopeFactory::class)]
final class LazyInternalScopeFactory implements InternalScopeFactory
Expand Down Expand Up @@ -46,6 +47,11 @@ final class LazyInternalScopeFactory implements InternalScopeFactory

private ?AttributeReflectionFactory $attributeReflectionFactory = null;

private ?self $twin = null;

/** @var WeakReference<self>|null */
private ?WeakReference $origin = null;

/**
* @param callable(Node $node, Scope $scope): void|null $nodeCallback
*/
Expand Down Expand Up @@ -131,12 +137,43 @@ public function create(

public function toFiberFactory(): InternalScopeFactory
{
return new self($this->container, $this->nodeCallback, true);
return $this->fiber ? $this : $this->twin();
}

public function toMutatingFactory(): InternalScopeFactory
{
return new self($this->container, $this->nodeCallback, false);
return $this->fiber ? $this->twin() : $this;
}

/**
* The factory for the other scope flavour, created once. Scopes switch
* flavour constantly, and a fresh factory would start with empty memos —
* resolving every service above out of the container again on its first
* create().
*
* The pair is held one way strongly and the other way weakly: a factory
* belongs to a single analysed file (ScopeFactory::create() makes one per
* file, closing over that file's node callback), and a strong cycle here
* would keep every file's callback alive for the whole run — PHPStan runs
* with the cycle collector disabled, so nothing would ever free it.
*/
private function twin(): self
{
if ($this->twin !== null) {
return $this->twin;
}

if ($this->origin !== null) {
$origin = $this->origin->get();
if ($origin !== null) {
return $origin;
}
}

$this->twin = new self($this->container, $this->nodeCallback, !$this->fiber);
$this->twin->origin = WeakReference::create($this);

return $this->twin;
}

}
Loading