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
28 changes: 12 additions & 16 deletions src/Plugin/Generator/ProtoGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ private function generateMessage(
return $namespace;
}

$namespace->addUse('Thesis\Protobuf\Reflection');
$runtime = new RuntimeImports($namespace);

$constructor = $classType->addMethod('__construct');

Expand Down Expand Up @@ -338,25 +338,21 @@ private function generateMessage(
$type = null;

if ($field->map !== null) {
$keyType = $this->types->create($field->map->key);
$valueType = $this->types->create($field->map->value);
$keyType = $this->types->create($field->map->key, $runtime);
$valueType = $this->types->create($field->map->value, $runtime);
$map = $runtime->protobuf('Map');

$type = new TypeDeclaration(
phpType: 'Protobuf\Map',
reflectionType: Literal::new('Reflection\MapT', [$keyType->reflectionType, $valueType->reflectionType]),
phpType: $map,
reflectionType: Literal::new($runtime->reflection('MapT'), [$keyType->reflectionType, $valueType->reflectionType]),
nullable: false,
isMap: true,
docType: "Protobuf\\Map<{$keyType->resolvedType()}, {$valueType->resolvedType()}>",
default: Literal::new('Protobuf\Map'),
uses: ['Thesis\Protobuf'],
docType: "{$map}<{$keyType->resolvedType()}, {$valueType->resolvedType()}>",
default: Literal::new($map),
);
}

$type ??= $this->types->create($field);

foreach ($type->uses as $use) {
$namespace->addUse($use);
}
$type ??= $this->types->create($field, $runtime);

$repeated = $field->label === FieldDescriptorProto\Label::LABEL_REPEATED && !$type->isMap;
$required = $field->label === FieldDescriptorProto\Label::LABEL_REQUIRED || $features?->fieldPresence === FeatureSet\FieldPresence::LEGACY_REQUIRED;
Expand All @@ -382,7 +378,7 @@ private function generateMessage(
$parameters[] = $features?->repeatedFieldEncoding === null || $features->repeatedFieldEncoding === FeatureSet\RepeatedFieldEncoding::PACKED;
}

$reflectionType = Literal::new('Reflection\ListT', $parameters);
$reflectionType = Literal::new($runtime->reflection('ListT'), $parameters);
}

$default = $nullable ? null : $type->default;
Expand All @@ -396,7 +392,7 @@ private function generateMessage(

$parameter
->setType($phpType)
->addAttribute('Reflection\Field', [
->addAttribute($runtime->reflection('Field'), [
$field->number,
$reflectionType,
])
Expand Down Expand Up @@ -456,7 +452,7 @@ private function generateMessage(
->setType($this->namespacer->fqcn("{$message->path}.{$oneofInterfaces[$idx]}"))
->setNullable()
->setDefaultValue(null)
->addAttribute('Reflection\OneOf', [
->addAttribute($runtime->reflection('OneOf'), [
array_map(
fn(Parser\FieldDescriptor $variant) => new Literal(
\sprintf(
Expand Down
63 changes: 63 additions & 0 deletions src/Plugin/Generator/RuntimeImports.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

declare(strict_types=1);

namespace Thesis\Protoc\Plugin\Generator;

use Nette\PhpGenerator\PhpNamespace;

/**
* The names a generated message file refers to the runtime thesis/protobuf with: `Reflection\Field`
* through `use Thesis\Protobuf\Reflection;`, `Protobuf\Map` through `use Thesis\Protobuf;`. The only place
* these names are decided: attributes, reflection types, the map type, its default and its docblock all take them from here.
*
* The import is added on the first reference, and the name is then asked from Nette, which prints the import:
* when a class of the namespace already owns the short name (a message named Reflection or Protobuf, compared
* case-insensitively), Nette imports the runtime under another alias (Reflection1), and the reference follows it.
* The file is printed without type resolving (see FileFactory), so nothing else would rewrite the reference.
*
* Create it only after the classes of the namespace are added: PhpNamespace::add() refuses a class whose name is
* already an alias, while addUse() steps aside for a class added before.
*
* @api
*/
final readonly class RuntimeImports
{
private const string PROTOBUF = 'Thesis\Protobuf';
private const string REFLECTION = 'Thesis\Protobuf\Reflection';

public function __construct(
private PhpNamespace $namespace,
) {}

/**
* @param non-empty-string $name a class of Thesis\Protobuf\Reflection, optionally followed by a member: "Field", "StringT::T"
*/
public function reflection(string $name): string
{
return $this->refer(self::REFLECTION, $name);
}

/**
* @param non-empty-string $name a class of Thesis\Protobuf: "Map"
*/
public function protobuf(string $name): string
{
return $this->refer(self::PROTOBUF, $name);
}

/**
* @param non-empty-string $import
* @param non-empty-string $name
*/
private function refer(string $import, string $name): string
{
$this->namespace->addUse($import);

$separator = strpos($name, '::');
$class = $separator === false ? $name : substr($name, 0, $separator);
$member = $separator === false ? '' : substr($name, $separator);

return $this->namespace->simplifyName("{$import}\\{$class}") . $member;
}
}
4 changes: 0 additions & 4 deletions src/Plugin/Generator/TypeDeclaration.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,13 @@
*/
final readonly class TypeDeclaration
{
/**
* @param list<non-empty-string> $uses
*/
public function __construct(
public string $phpType,
public Literal $reflectionType,
public bool $nullable = false,
public bool $isMap = false,
public ?string $docType = null,
public mixed $default = null,
public array $uses = [],
) {}

public function resolvedType(): string
Expand Down
34 changes: 17 additions & 17 deletions src/Plugin/Generator/TypeDeclarationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public function __construct(
private Dependency\Graph $graph,
) {}

public function create(Parser\FieldDescriptor $field): TypeDeclaration
public function create(Parser\FieldDescriptor $field, RuntimeImports $runtime): TypeDeclaration
{
if ($field->typeName !== null) {
$fieldType = $this->graph->get($field->typeName);
Expand All @@ -41,7 +41,7 @@ public function create(Parser\FieldDescriptor $field): TypeDeclaration

return new TypeDeclaration(
phpType: $fieldType->fqcn,
reflectionType: Literal::new('Reflection\\' . ($isEnum ? 'EnumT' : 'ObjectT'), [
reflectionType: Literal::new($runtime->reflection($isEnum ? 'EnumT' : 'ObjectT'), [
new Literal("{$fieldType->fqcn}::class"),
]),
nullable: !$isEnum,
Expand All @@ -55,17 +55,17 @@ public function create(Parser\FieldDescriptor $field): TypeDeclaration
Type::TYPE_DOUBLE => new TypeDeclaration(
phpType: 'float',
reflectionType: new Literal(match ($type) {
Type::TYPE_FLOAT => 'Reflection\FloatT::T',
Type::TYPE_DOUBLE => 'Reflection\DoubleT::T',
Type::TYPE_FLOAT => $runtime->reflection('FloatT::T'),
Type::TYPE_DOUBLE => $runtime->reflection('DoubleT::T'),
}),
default: 0,
),
Type::TYPE_UINT64,
Type::TYPE_FIXED64 => new TypeDeclaration(
phpType: '\BcMath\Number',
reflectionType: new Literal(match ($type) {
Type::TYPE_UINT64 => 'Reflection\Uint64T::T',
Type::TYPE_FIXED64 => 'Reflection\Fixed64T::T',
Type::TYPE_UINT64 => $runtime->reflection('Uint64T::T'),
Type::TYPE_FIXED64 => $runtime->reflection('Fixed64T::T'),
}),
default: Literal::new('\BcMath\Number', [0]),
),
Expand All @@ -79,28 +79,28 @@ public function create(Parser\FieldDescriptor $field): TypeDeclaration
Type::TYPE_SINT64 => new TypeDeclaration(
phpType: 'int',
reflectionType: new Literal(match ($type) {
Type::TYPE_INT32 => 'Reflection\Int32T::T',
Type::TYPE_FIXED32 => 'Reflection\Fixed32T::T',
Type::TYPE_UINT32 => 'Reflection\Uint32T::T',
Type::TYPE_SFIXED32 => 'Reflection\SFixed32T::T',
Type::TYPE_SINT32 => 'Reflection\SInt32T::T',
Type::TYPE_INT64 => 'Reflection\Int64T::T',
Type::TYPE_SFIXED64 => 'Reflection\SFixed64T::T',
Type::TYPE_SINT64 => 'Reflection\SInt64T::T',
Type::TYPE_INT32 => $runtime->reflection('Int32T::T'),
Type::TYPE_FIXED32 => $runtime->reflection('Fixed32T::T'),
Type::TYPE_UINT32 => $runtime->reflection('Uint32T::T'),
Type::TYPE_SFIXED32 => $runtime->reflection('SFixed32T::T'),
Type::TYPE_SINT32 => $runtime->reflection('SInt32T::T'),
Type::TYPE_INT64 => $runtime->reflection('Int64T::T'),
Type::TYPE_SFIXED64 => $runtime->reflection('SFixed64T::T'),
Type::TYPE_SINT64 => $runtime->reflection('SInt64T::T'),
}),
default: 0,
),
Type::TYPE_BOOL => new TypeDeclaration(
phpType: 'bool',
reflectionType: new Literal('Reflection\BoolT::T'),
reflectionType: new Literal($runtime->reflection('BoolT::T')),
default: false,
),
Type::TYPE_STRING,
Type::TYPE_BYTES => new TypeDeclaration(
phpType: 'string',
reflectionType: new Literal(match ($type) {
Type::TYPE_STRING => 'Reflection\StringT::T',
Type::TYPE_BYTES => 'Reflection\BytesT::T',
Type::TYPE_STRING => $runtime->reflection('StringT::T'),
Type::TYPE_BYTES => $runtime->reflection('BytesT::T'),
}),
default: '',
),
Expand Down
58 changes: 58 additions & 0 deletions tests/GeneratedCode/samples/runtime_import_alias.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

/**
* Populated messages of the runtime_import_alias snapshot case, keyed by label (see GeneratedCodeTest).
*/

use Runtime\Alias\Field;
use Runtime\Alias\Holder;
use Runtime\Alias\Item;
use Runtime\Alias\Kind;
use Runtime\Alias\Map;
use Runtime\Alias\OneOf;
use Runtime\Alias\Outer;
use Runtime\Alias\Protobuf;
use Runtime\Alias\Reflection;
use Runtime\Alias\StringT;
use Runtime\Alias\Variants;
use Thesis\Protobuf\Map as RuntimeMap;

return [
'message named after the Reflection alias, oneof set to a scalar' => new Reflection(
scalar: 'scalar',
numbers: [1, -2, 3],
kind: Kind::KIND_ONE,
item: new Item('item'),
items: RuntimeMap::fromArray(['a' => new Item('a'), 'b' => new Item('b')]),
choice: new Reflection\ChoiceText('text'),
),
'message named after the Reflection alias, oneof set to a message' => new Reflection(
choice: new Reflection\ChoiceObject(new Item('object')),
),
'message named after the Protobuf alias' => new Protobuf(
counts: RuntimeMap::fromArray(['one' => 1, 'two' => 2]),
name: 'protobuf',
),
'nested message named after the Reflection alias' => new Outer(
inner: new Outer\Reflection('a', RuntimeMap::fromArray([1 => 'one', 2 => 'two'])),
),
'oneof variant differing from the Reflection alias in case' => new Variants(
reflect: new Variants\ReflectIon('ion'),
),
'oneof variant next to it' => new Variants(
reflect: new Variants\ReflectOther(7),
),
'messages named after runtime classes' => new Holder(
reflection: new Reflection(scalar: 'r'),
protobuf: new Protobuf(counts: RuntimeMap::fromArray(['c' => 3])),
nested: new Outer\Reflection('n'),
field: new Field('field'),
map: new Map(RuntimeMap::fromArray(['k' => 'v'])),
oneOf: new OneOf(new OneOf\ValueI(5)),
stringT: new StringT('string'),
list: [new Reflection(scalar: 'first'), new Reflection(kind: Kind::KIND_ONE)],
byName: RuntimeMap::fromArray(['x' => new Reflection(numbers: [9])]),
),
];
87 changes: 87 additions & 0 deletions tests/fixtures/runtime_import_alias/runtime_import_alias.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
syntax = "proto3";

package runtime.alias;

// The generated classes import the runtime as `use Thesis\Protobuf\Reflection;` (and `use Thesis\Protobuf;` for
// map fields) and refer to it through that alias. A class with the same short name takes the alias, so the import
// gets another one, and the references have to follow it.

enum Kind {
KIND_UNSPECIFIED = 0;
KIND_ONE = 1;
}

message Item {
string name = 1;
}

// Takes the short name of `use Thesis\Protobuf\Reflection`.
message Reflection {
string scalar = 1;
repeated int32 numbers = 2;
Kind kind = 3;
Item item = 4;
map<string, Item> items = 5;

oneof choice {
string text = 6;
Item object = 7;
}
}

// Takes the short name of `use Thesis\Protobuf`, which only map fields import.
message Protobuf {
map<string, int32> counts = 1;
string name = 2;
}

// A nested class is declared in a namespace of its own, the parent keeps the plain import.
message Outer {
message Reflection {
string a = 1;
map<int32, string> m = 2;
}

Reflection inner = 1;
}

// The variant class ReflectIon differs from the alias Reflection only in case, which PHP does not tell apart.
message Variants {
oneof reflect {
string ion = 1;
int32 other = 2;
}
}

// Named after classes referred to through the alias, not after the alias itself: no conflict.
message Field {
string a = 1;
}

message Map {
map<string, string> m = 1;
}

message OneOf {
oneof value {
string s = 1;
int32 i = 2;
}
}

message StringT {
string s = 1;
}

// Refers to the messages above as field types, by fully qualified name.
message Holder {
Reflection reflection = 1;
Protobuf protobuf = 2;
Outer.Reflection nested = 3;
Field field = 4;
Map map = 5;
OneOf one_of = 6;
StringT string_t = 7;
repeated Reflection list = 8;
map<string, Reflection> by_name = 9;
}
Loading