Skip to content
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,7 @@ To avoid having to generate these types each time, it is recommended to use libr
- [ ] `extensions`
- [ ] `groups`
- [x] `nested types`
- [x] `import public`
- [x] `packed repeated`
- [x] `oneof`
- [x] `grpc`
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"composer-runtime-api": "^2.2",
"nette/php-generator": "^4.2.1",
"thesis/package-version": "^0.1.2",
"thesis/protobuf": "^0.2",
"thesis/protobuf": "^0.2.2",
"thesis/protobuf-compiler-types": "^0.3",
"thesis/protobuf-descriptor-types": "^0.3",
"thesis/protoregistry": "^0.1.2"
Expand Down
39 changes: 38 additions & 1 deletion src/Plugin/Dependency/Registry.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,16 @@ private function createIndex(Parser\Request $request, NamespaceResolver $namespa
private function mergeIndex(Parser\Request $request): void
{
foreach ($request as $name => $descriptor) {
$visible = [$name];
$seen = [$name => true];

foreach ($descriptor->dependencies as $dep) {
$this->collectExported($request, $dep, $visible, $seen);
}

$indexes = [];

foreach ([$name, ...$descriptor->dependencies] as $dep) {
foreach ($visible as $dep) {
if (isset($this->index[$dep])) {
$indexes = [
...$indexes,
Expand All @@ -75,6 +82,36 @@ private function mergeIndex(Parser\Request $request): void
}
}

/**
* Collects an imported file along with everything it re-exports through "import public",
* at any depth. A plain import of the imported file is not re-exported.
*
* @param list<string> $visible
* @param array<string, true> $seen
* @param-out list<string> $visible
*/
private function collectExported(Parser\Request $request, string $file, array &$visible, array &$seen): void
{
if (isset($seen[$file])) {
return;
}

$seen[$file] = true;
$visible[] = $file;

$descriptor = $request->descriptors[$file] ?? null;

if ($descriptor === null) {
return;
}

foreach ($descriptor->file->publicDependency as $idx) {
if (isset($descriptor->dependencies[$idx])) {
$this->collectExported($request, $descriptor->dependencies[$idx], $visible, $seen);
}
}
}

private function createDependencyGraph(Parser\Request $request): void
{
foreach ($request->descriptors as $name => $proto) {
Expand Down
110 changes: 110 additions & 0 deletions tests/CompilerImportPublicTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

declare(strict_types=1);

namespace Thesis\Protoc;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Thesis\Google\Protobuf\Compiler\CodeGeneratorRequest;
use Thesis\Protobuf\Decoder;
use Thesis\Protobuf\Encoder;
use Thesis\Protoc\Plugin\Compiler;
use Thesis\Protoc\Plugin\Dependency\Registry;

/**
* The import_public snapshot case is generated with all its files in file_to_generate. The usual run, though,
* generates only the importer, and the files it reaches through "import public" come only as dependencies
* (proto_file). The request protoc sent for the case is narrowed to one file here: the code generated for it must
* be the same as in the snapshot.
*/
#[CoversClass(Compiler::class)]
#[CoversClass(Registry::class)]
final class CompilerImportPublicTest extends TestCase
{
private const string CASE = 'import_public';

/**
* @param non-empty-string $file
* @param list<string> $expected generated files, autoload.metadata.php aside (it is shared by the whole case)
*/
#[DataProvider('provideOnlyImporterIsGeneratedCases')]
public function testOnlyImporterIsGenerated(string $file, array $expected): void
{
$request = self::request();

self::assertContains($file, $request->fileToGenerate);

$request = new CodeGeneratorRequest(
fileToGenerate: [$file],
parameter: $request->parameter,
protoFile: $request->protoFile,
compilerVersion: $request->compilerVersion,
);

$generated = [];

foreach (new Compiler(Encoder\Builder::buildDefault(), __DIR__ . '/../map.json')->compile($request) as $out) {
self::assertNotNull($out->name);
self::assertNotNull($out->content);

if (basename($out->name) !== 'autoload.metadata.php') {
$generated[$out->name] = $out->content;
}
}

ksort($generated);

self::assertSame($expected, array_keys($generated));

foreach ($generated as $name => $content) {
$snapshot = file_get_contents(__DIR__ . '/snapshots/' . self::CASE . "/{$name}");
self::assertIsString($snapshot);
self::assertSame(self::normalize($snapshot), self::normalize($content), $name);
}
}

/**
* @return iterable<string, array{non-empty-string, list<string>}>
*/
public static function provideOnlyImporterIsGeneratedCases(): iterable
{
yield 'messages, maps and a service with re-exported types' => ['a.proto', [
'T/Pub/A/A.php',
'T/Pub/A/DescriptorRegistry.php',
'T/Pub/A/LookupClient.php',
'T/Pub/A/LookupServer.php',
'T/Pub/A/LookupServerRegistry.php',
]];

yield 'enum defaults with a re-exported enum' => ['legacy.proto', [
'T/Pub/Legacy/DescriptorRegistry.php',
'T/Pub/Legacy/Legacy.php',
]];

yield 'file using the types it re-exports' => ['reexport.proto', [
'T/Pub/Re/DescriptorRegistry.php',
'T/Pub/Re/Wrapper.php',
]];
}

private static function request(): CodeGeneratorRequest
{
$root = getenv('TESTDATA_DIR');
$root = \is_string($root) && $root !== '' ? $root : \dirname(__DIR__) . '/var/testdata';

$hex = file_get_contents($root . '/' . self::CASE . '/request.hex');
self::assertIsString($hex, 'No generated testdata found. Run `make test` or `make generate-testdata` first.');

$bytes = hex2bin($hex);
self::assertIsString($bytes);

return Decoder\Builder::buildDefault()->decode($bytes, CodeGeneratorRequest::class);
}

private static function normalize(string $content): string
{
return (string) preg_replace('/thesis\/protoc-plugin — v[^\n]+/', 'thesis/protoc-plugin — v<version>', $content);
}
}
41 changes: 41 additions & 0 deletions tests/GeneratedCode/samples/import_public.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

/**
* Populated messages of the import_public snapshot case (types visible only through "import public"), keyed by label
* (see GeneratedCodeTest).
*/

use T\Pub\A\A;
use T\Pub\C\C;
use T\Pub\D\D;
use T\Pub\Legacy\Legacy;
use T\Pub\Re\Wrapper;
use Test\ImportPublic\Custom\Box;
use Test\ImportPublic\Custom\Color;
use Thesis\Protobuf\Map;

return [
'all fields set' => new A(
c: new C('c', new D('nested')),
d: new D('d'),
box: new Box(new Box\Item('in box'), Color::COLOR_RED),
item: new Box\Item('item'),
color: Color::COLOR_GREEN,
byName: Map::fromArray(['first' => new D('1'), 'second' => new D('2')]),
colors: Map::fromArray([1 => Color::COLOR_RED, 2 => Color::COLOR_GREEN]),
list: [new C('x'), new C('y', new D('z'))],
maybeColor: Color::COLOR_UNSPECIFIED,
),
're-exporting file using the re-exported types' => new Wrapper(
box: new Box(new Box\Item('wrapped')),
color: Color::COLOR_RED,
c: new C('c'),
d: new D('d'),
),
'enum defaults of a re-exported enum' => new Legacy(
color: Color::COLOR_RED,
requiredColor: Color::COLOR_GREEN,
),
];
Loading