From b4ab3df2ec85fbe477d7721344a8cd3630b437a1 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sun, 16 Aug 2026 13:59:28 +0900 Subject: 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) --- scripts/plugin-stub-generator/src/Generator.php | 29 +-- .../plugin-stub-generator/src/GuardGenerator.php | 215 +++++++++++++++++++++ scripts/plugin-stub-generator/src/Report.php | 33 +++- scripts/plugin-stub-generator/src/SourceFile.php | 21 ++ 4 files changed, 271 insertions(+), 27 deletions(-) create mode 100644 scripts/plugin-stub-generator/src/GuardGenerator.php (limited to 'scripts/plugin-stub-generator/src') diff --git a/scripts/plugin-stub-generator/src/Generator.php b/scripts/plugin-stub-generator/src/Generator.php index dd62da60..0b8ef037 100644 --- a/scripts/plugin-stub-generator/src/Generator.php +++ b/scripts/plugin-stub-generator/src/Generator.php @@ -159,7 +159,7 @@ final class Generator return []; } $surface = []; - $parentFqcn = $class->extends === null ? null : $this->resolvedName($class->extends); + $parentFqcn = $class->extends === null ? null : SourceFile::resolvedName($class->extends); if ($parentFqcn !== null) { $surface = $this->surfaces[$parentFqcn] ?? $this->surfaceFromRealClass($parentFqcn); } @@ -195,7 +195,7 @@ final class Generator . '; only rust-proxy and contract classes can become proxy stubs'; } - $parentFqcn = $class->extends === null ? null : $this->resolvedName($class->extends); + $parentFqcn = $class->extends === null ? null : SourceFile::resolvedName($class->extends); $isRoot = $parentFqcn === null; if ($parentFqcn !== null && !isset($this->targetSet[$parentFqcn])) { if (isset($this->runtimeSet[$parentFqcn])) { @@ -348,7 +348,7 @@ final class Generator $header = "// Generated by scripts/plugin-stub-generator; do not edit by hand.\n" . "// Proxy stub for $fqcn: the public surface forwards to the Rust-side entity over RPC."; $text = "namespace};\n\n"; - $uses = $this->usedImports($file, $decl . "\n" . $body); + $uses = $file->importsUsedBy($decl . "\n" . $body); if ($uses !== '') { $text .= $uses . "\n\n"; } @@ -446,11 +446,11 @@ final class Generator } $out[] = $file; foreach ($file->classLike->extends as $parent) { - $visit($this->resolvedName($parent)); + $visit(SourceFile::resolvedName($parent)); } }; foreach ($class->implements as $interface) { - $visit($this->resolvedName($interface)); + $visit(SourceFile::resolvedName($interface)); } return $out; } @@ -527,23 +527,4 @@ final class Generator } return $fingerprint; } - - /** The original file's imports, restricted to names the emitted stub actually uses. */ - private function usedImports(SourceFile $file, string $emittedText): string - { - $kept = []; - foreach ($file->aliases as $alias => $fqcn) { - if (preg_match('/(?getAttribute('resolvedName'); - return $resolved instanceof Name ? $resolved->toString() : $name->toString(); - } } 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 @@ + */ + private array $errors = []; + + /** @var array */ + private array $guardSet = []; + + /** @var array */ + private array $providedSet = []; + + /** @var list `Ancestor::member` entries the class being emitted cannot redeclare */ + private array $inheritedFinals = []; + + /** + * @param list $targets FQCNs to emit a guard for + * @param list $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 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 = "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 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 }"; + } + +} diff --git a/scripts/plugin-stub-generator/src/Report.php b/scripts/plugin-stub-generator/src/Report.php index 92e0565e..758a1768 100644 --- a/scripts/plugin-stub-generator/src/Report.php +++ b/scripts/plugin-stub-generator/src/Report.php @@ -7,8 +7,11 @@ namespace Shirabe\PluginStubGenerator; /** The classifier report (scripts/plugin-class-classifier/report.json). */ final class Report { - /** @param array $categories fqcn => category */ - private function __construct(private readonly array $categories) + /** + * @param array $categories fqcn => category + * @param array $kinds fqcn => class / interface / trait / enum + */ + private function __construct(private readonly array $categories, private readonly array $kinds) { } @@ -24,14 +27,38 @@ final class Report throw new GenerationError(["$path records classification violations; fix the classifier lists first"]); } $categories = []; + $kinds = []; foreach ($data['classes'] as $class) { $categories[$class['fqcn']] = $class['category']; + $kinds[$class['fqcn']] = $class['kind']; } - return new self($categories); + return new self($categories, $kinds); } public function category(string $fqcn): ?string { return $this->categories[$fqcn] ?? null; } + + public function kind(string $fqcn): ?string + { + return $this->kinds[$fqcn] ?? null; + } + + /** + * The FQCNs of the given categories, in report order. + * + * @param list $categories + * @return list + */ + public function inCategories(array $categories): array + { + $out = []; + foreach ($this->categories as $fqcn => $category) { + if (in_array($category, $categories, true)) { + $out[] = $fqcn; + } + } + return $out; + } } diff --git a/scripts/plugin-stub-generator/src/SourceFile.php b/scripts/plugin-stub-generator/src/SourceFile.php index 771e83a8..e20bf00f 100644 --- a/scripts/plugin-stub-generator/src/SourceFile.php +++ b/scripts/plugin-stub-generator/src/SourceFile.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Shirabe\PluginStubGenerator; +use PhpParser\Node\Name; use PhpParser\Node\Stmt\ClassLike; use PhpParser\Node\Stmt\GroupUse; use PhpParser\Node\Stmt\Namespace_; @@ -83,4 +84,24 @@ final class SourceFile { return implode("\n", array_slice($this->lines, $startLine - 1, $endLine - $startLine + 1)); } + + /** This file's imports, restricted to the names the emitted text actually uses. */ + public function importsUsedBy(string $emittedText): string + { + $kept = []; + foreach ($this->aliases as $alias => $fqcn) { + if (preg_match('/(?getAttribute('resolvedName'); + return $resolved instanceof Name ? $resolved->toString() : $name->toString(); + } } -- cgit v1.3.1-4-g156e