aboutsummaryrefslogtreecommitdiffhomepage
path: root/scripts/plugin-stub-generator/src/GuardGenerator.php
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2026-08-16 13:59:28 +0900
committernsfisis <nsfisis@gmail.com>2026-08-16 13:59:28 +0900
commitb4ab3df2ec85fbe477d7721344a8cd3630b437a1 (patch)
treeeb618cbbdfa46cf829031f9c427dc09ef7584831 /scripts/plugin-stub-generator/src/GuardGenerator.php
parentbaf9aff3134ac5a10260d3be421a2c17a0180d64 (diff)
downloadphp-shirabe-b4ab3df2ec85fbe477d7721344a8cd3630b437a1.tar.gz
php-shirabe-b4ab3df2ec85fbe477d7721344a8cd3630b437a1.tar.zst
php-shirabe-b4ab3df2ec85fbe477d7721344a8cd3630b437a1.zip
feat(plugin): guard Rust-owned classes the worker has no proxy for
The worker's autoloader fell through to the real Composer source for every Rust-owned FQCN without a proxy stub, so plugin code doing `new Filesystem()` or subclassing `LibraryInstaller` silently ran on a second instance the Rust side never sees. An unimplemented part of the plugin API has to fail with an explicit error naming it, not quietly work on a disconnected copy. The stub generator now emits a guard class for each of those FQCNs: the real declaration, hierarchy and constants, with every constructor and method raising an explicit error. References satisfied by the declaration alone (`instanceof`, `X::class`, `Link::TYPE_REQUIRE`) keep working. Two FQCNs stay resolvable to the real class, each listed with the worker-side mechanism that makes a natively constructed instance correct. The error had nowhere to go: `Installer::run` dropped the `Result` of both `dispatch_script` calls, so an exception from a listener ended in exit 0. Both propagate now, the way the exception does upstream. Three real-plugin E2E comparisons stop at a guard and are ignored, each naming the class it needs. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Diffstat (limited to 'scripts/plugin-stub-generator/src/GuardGenerator.php')
-rw-r--r--scripts/plugin-stub-generator/src/GuardGenerator.php215
1 files changed, 215 insertions, 0 deletions
diff --git a/scripts/plugin-stub-generator/src/GuardGenerator.php b/scripts/plugin-stub-generator/src/GuardGenerator.php
new file mode 100644
index 00000000..e471f1a3
--- /dev/null
+++ b/scripts/plugin-stub-generator/src/GuardGenerator.php
@@ -0,0 +1,215 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Shirabe\PluginStubGenerator;
+
+use PhpParser\Node\Name;
+use PhpParser\Node\Stmt\Class_;
+use PhpParser\Node\Stmt\ClassMethod;
+
+/**
+ * Emits the guard classes: same FQCN, same hierarchy and constants as the real Composer class,
+ * but every constructor and method raises an explicit error. They cover the classes whose entity
+ * the Rust side owns and that have no proxy stub, so the worker's autoloader can no longer fall
+ * through to the real implementation and run a second instance the Rust side never sees.
+ *
+ * A declaration-only reference (`instanceof`, `X::class`, a constant) keeps working; only running
+ * the code fails.
+ */
+final class GuardGenerator
+{
+ /** @var list<string> */
+ private array $errors = [];
+
+ /** @var array<string, true> */
+ private array $guardSet = [];
+
+ /** @var array<string, true> */
+ private array $providedSet = [];
+
+ /** @var list<string> `Ancestor::member` entries the class being emitted cannot redeclare */
+ private array $inheritedFinals = [];
+
+ /**
+ * @param list<string> $targets FQCNs to emit a guard for
+ * @param list<string> $provided FQCNs the worker resolves to a proxy stub or a hand-written
+ * runtime class; a guard never reproduces their members, since
+ * those declarations already shadow the real class
+ */
+ public function __construct(
+ private readonly Project $project,
+ private readonly NamePrinter $printer,
+ private readonly array $targets,
+ array $provided,
+ ) {
+ foreach ($targets as $fqcn) {
+ $this->guardSet[$fqcn] = true;
+ }
+ foreach ($provided as $fqcn) {
+ $this->providedSet[$fqcn] = true;
+ }
+ }
+
+ /** @return array<string, string> relative guard path => file content */
+ public function generate(): array
+ {
+ $files = [];
+ foreach ($this->targets as $fqcn) {
+ $files[str_replace('\\', '/', $fqcn) . '.php'] = $this->emitClass($fqcn);
+ }
+ if ($this->errors !== []) {
+ throw new GenerationError($this->errors);
+ }
+ return $files;
+ }
+
+ private function emitClass(string $fqcn): string
+ {
+ $file = $this->project->sourceFor($fqcn);
+ $class = $file->classLike;
+ if (!$class instanceof Class_) {
+ $this->errors[] = "$fqcn is not a class";
+ return '';
+ }
+
+ // Constants and public static properties are compile-time data with no instance behind
+ // them; they are copied verbatim, visibility included, so that the references a guard is
+ // meant to keep working (`Link::TYPE_REQUIRE` and friends) resolve to the real values.
+ $data = [];
+ foreach ($class->getConstants() as $constant) {
+ $data[] = $file->verbatim($constant->getStartLine(), $constant->getEndLine());
+ }
+ foreach ($class->getProperties() as $property) {
+ if ($property->isPublic() && $property->isStatic()) {
+ $data[] = $file->verbatim($property->getStartLine(), $property->getEndLine());
+ }
+ }
+
+ $methods = [];
+ $this->inheritedFinals = [];
+ $closure = $this->methodClosure($fqcn);
+ if (!isset($closure['__construct'])) {
+ // Nothing in the hierarchy declares one, so PHP would hand out the implicit
+ // constructor. The guard declares its own to close that door.
+ $methods[] = " public function __construct()\n {\n"
+ . " \\ShirabeUnsupportedClass::fail(self::class, '__construct');\n }";
+ }
+ foreach ($closure as $lowerName => [$method, $declaringFile]) {
+ if ($method->isPrivate() || $lowerName === '__destruct') {
+ // A private method is reachable only from the code the guard replaces, and a
+ // destructor that throws would fire while an exception is already unwinding.
+ continue;
+ }
+ $methods[] = $this->renderMethod($class, $method, $declaringFile);
+ }
+
+ $decl = ($class->isAbstract() ? 'abstract ' : '') . ($class->isFinal() ? 'final ' : '')
+ . 'class ' . $class->name?->toString();
+ if ($class->extends !== null) {
+ $decl .= ' extends ' . $this->printer->renderName($class->extends, $file);
+ }
+ $interfaces = array_map(fn (Name $n): string => $this->printer->renderName($n, $file), $class->implements);
+ if ($interfaces !== []) {
+ $decl .= ' implements ' . implode(', ', $interfaces);
+ }
+
+ $body = implode("\n\n", array_merge($data === [] ? [] : [implode("\n", $data)], $methods));
+
+ $header = "// Generated by scripts/plugin-stub-generator; do not edit by hand.\n"
+ . "// Guard for $fqcn.\n"
+ . "// The Rust side owns this class and the worker has no proxy for it, so this\n"
+ . "// declaration shadows the real one: the constants and the hierarchy stay, while\n"
+ . "// constructing it or calling anything on it raises an explicit error.";
+ foreach ($this->inheritedFinals as $member) {
+ $header .= "\n// $member() is final, so it keeps running the real implementation here.";
+ }
+ $text = "<?php\n\n$header\n\nnamespace {$file->namespace};\n\n";
+ $uses = $file->importsUsedBy($decl . "\n" . $body);
+ if ($uses !== '') {
+ $text .= $uses . "\n\n";
+ }
+ return $text . $decl . "\n{\n" . ($body === '' ? '' : $body . "\n") . "}\n";
+ }
+
+ /**
+ * Every method a guard must redeclare: its own (traits included), plus the ones it would
+ * otherwise inherit from real ancestors. The walk stops at an ancestor that is guarded or
+ * shadowed by a stub, since that declaration carries the members from there on up.
+ *
+ * @return array<string, array{ClassMethod, SourceFile}> lowercased name => method and the
+ * file its signature is written in
+ */
+ private function methodClosure(string $fqcn): array
+ {
+ $file = $this->project->sourceFor($fqcn);
+ $class = $file->classLike;
+ $methods = [];
+ foreach ($class->getMethods() as $method) {
+ $methods[strtolower($method->name->toString())] ??= [$method, $file];
+ }
+ foreach ($class->getTraitUses() as $traitUse) {
+ foreach ($traitUse->traits as $trait) {
+ foreach ($this->methodClosure(SourceFile::resolvedName($trait)) as $name => $entry) {
+ $methods[$name] ??= $entry;
+ }
+ }
+ }
+ $parent = $class instanceof Class_ && $class->extends !== null
+ ? SourceFile::resolvedName($class->extends)
+ : null;
+ // A PHP builtin ancestor (FilterIterator, ...) has no source file to read; its methods
+ // work on internal state that only its own constructor sets up, which the guard blocks.
+ $isInternal = $parent !== null && class_exists($parent, false)
+ && (new \ReflectionClass($parent))->isInternal();
+ if ($parent !== null && !$isInternal
+ && !isset($this->guardSet[$parent]) && !isset($this->providedSet[$parent])) {
+ foreach ($this->methodClosure($parent) as $name => $entry) {
+ if (isset($methods[$name])) {
+ continue;
+ }
+ if ($entry[0]->isFinal()) {
+ // PHP refuses the redeclaration, so this member keeps running the real
+ // implementation; emitClass records it in the guard's header.
+ $this->inheritedFinals[] = $parent . '::' . $entry[0]->name->toString();
+ continue;
+ }
+ $methods[$name] = $entry;
+ }
+ }
+ return $methods;
+ }
+
+ private function renderMethod(Class_ $class, ClassMethod $method, SourceFile $target): string
+ {
+ $name = $method->name->toString();
+ $params = [];
+ foreach ($method->params as $param) {
+ $rendered = '';
+ if ($param->type !== null) {
+ $rendered = $this->printer->renderType($param->type, $target) . ' ';
+ }
+ // A promoted constructor property declares state the guard has no use for; the
+ // parameter itself is kept so the signature a caller sees does not change.
+ $rendered .= ($param->byRef ? '&' : '') . ($param->variadic ? '...' : '') . '$' . $param->var->name;
+ if ($param->default !== null) {
+ $rendered .= ' = ' . $this->printer->renderExpr($param->default, $target);
+ }
+ $params[] = $rendered;
+ }
+
+ $abstract = $method->isAbstract() && $class->isAbstract();
+ $returnType = $this->printer->renderType($method->returnType, $target);
+ $signature = ($abstract ? 'abstract ' : '') . ($method->isFinal() ? 'final ' : '')
+ . ($method->isPublic() ? 'public' : 'protected')
+ . ($method->isStatic() ? ' static' : '')
+ . ' function ' . ($method->byRef ? '&' : '') . $name . '(' . implode(', ', $params) . ')'
+ . ($returnType === '' ? '' : ": $returnType");
+ if ($abstract) {
+ return " $signature;";
+ }
+ return " $signature\n {\n"
+ . " \\ShirabeUnsupportedClass::fail(self::class, '$name');\n }";
+ }
+
+}