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
16 changes: 13 additions & 3 deletions src/Plugin/Generator/ProtoGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ private static function claimClassName(array &$owners, Parser\MessageDescriptor
/**
* @param list<string> $implements
* @param array<int, string> $oneofInterfaces names of the oneof interfaces, see oneofInterfaceNames()
* @param bool $oneofVariant whether $message is the class of a oneof variant, see generateOneofVariant()
* @throws CodeCannotBeGenerated
*/
private function generateMessage(
Expand All @@ -285,6 +286,7 @@ private function generateMessage(
Parser\MessageDescriptor $message,
array $implements = [],
array $oneofInterfaces = [],
bool $oneofVariant = false,
): PhpNamespace {
$classType = new ClassType($className)
->setFinal()
Expand Down Expand Up @@ -364,9 +366,12 @@ private function generateMessage(
$repeated = $field->label === FieldDescriptorProto\Label::LABEL_REPEATED && !$type->isMap;
$required = $field->label === FieldDescriptorProto\Label::LABEL_REQUIRED || $features?->fieldPresence === FeatureSet\FieldPresence::LEGACY_REQUIRED;

$presence = $this->edition !== null
// The field of a oneof variant is not made nullable for presence in any syntax: the variant class exists
// only once the oneof is set to it, and the runtime writes its value even when that is the default one.
// A null inside a variant would only be a variant without a value, which is not written at all.
$presence = !$oneofVariant && ($this->edition !== null
? $features?->fieldPresence === FeatureSet\FieldPresence::EXPLICIT
: $field->optional;
: $field->optional);

$nullable = ($type->nullable || $presence) && !$repeated && !$required && !($field->type === FieldDescriptorProto\Type::TYPE_ENUM && $field->defaultValue !== null);

Expand Down Expand Up @@ -567,7 +572,7 @@ private function generateOneofVariant(
fqcn: $message->fqcn,
path: $path = "{$message->path}.{$className}",
fields: [
// Remove oneof index.
// The field as declared, only without the oneof index, so that it is generated as a plain field.
new Parser\FieldDescriptor(
name: $variant->name,
number: $variant->number,
Expand All @@ -577,6 +582,10 @@ private function generateOneofVariant(
comment: $variant->comment,
options: $variant->options,
optional: $variant->optional,
proto3Optional: $variant->proto3Optional,
defaultValue: $variant->defaultValue,
map: $variant->map,
features: $variant->features,
jsonName: $variant->jsonName,
),
],
Expand All @@ -589,6 +598,7 @@ private function generateOneofVariant(
[
$this->namespacer->fqcn("{$message->path}.{$interfaceName}"),
],
oneofVariant: true,
);
}

Expand Down
104 changes: 104 additions & 0 deletions tests/CompilerOneofVariantTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?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\Google\Protobuf\DescriptorProto;
use Thesis\Google\Protobuf\Edition;
use Thesis\Google\Protobuf\FeatureSet;
use Thesis\Google\Protobuf\FieldDescriptorProto;
use Thesis\Google\Protobuf\FieldDescriptorProto\Label;
use Thesis\Google\Protobuf\FieldDescriptorProto\Type;
use Thesis\Google\Protobuf\FieldOptions;
use Thesis\Google\Protobuf\FileDescriptorProto;
use Thesis\Google\Protobuf\OneofDescriptorProto;
use Thesis\Protobuf\Encoder;
use Thesis\Protoc\Exception\CodeCannotBeGenerated;
use Thesis\Protoc\Plugin\Compiler;
use Thesis\Protoc\Plugin\Generator\ProtoGenerator;

/**
* A oneof variant is generated from the field as declared, features included: a DELIMITED message variant is
* reported the same as a DELIMITED message field, instead of being generated as a length-prefixed message.
* The descriptors are what protoc sends for the proto in the comment. The rest of the field metadata a variant
* keeps is covered by the oneof_variants snapshot case.
*/
#[CoversClass(Compiler::class)]
#[CoversClass(ProtoGenerator::class)]
final class CompilerOneofVariantTest extends TestCase
{
#[DataProvider('provideDelimitedMessageIsReportedCases')]
public function testDelimitedMessageIsReported(?int $oneofIndex): void
{
$this->expectException(CodeCannotBeGenerated::class);
$this->expectExceptionMessage('DELIMITED message encoding are not supported');

self::compile($oneofIndex);
}

/**
* @return iterable<string, array{?int}>
*/
public static function provideDelimitedMessageIsReportedCases(): iterable
{
// edition = "2023"; message M { message Inner { int32 a = 1; } Inner d = 1 [features.message_encoding = DELIMITED]; }
yield 'field' => [null];

// edition = "2023"; message M { message Inner { int32 a = 1; } oneof o { Inner d = 1 [features.message_encoding = DELIMITED]; } }
yield 'oneof variant' => [0];
}

private static function compile(?int $oneofIndex): void
{
new Compiler(Encoder\Builder::buildDefault(), __DIR__ . '/../map.json')->compile(new CodeGeneratorRequest(
fileToGenerate: ['t.proto'],
protoFile: [
new FileDescriptorProto(
name: 't.proto',
package: 't',
messageType: [
new DescriptorProto(
name: 'M',
field: [
new FieldDescriptorProto(
name: 'd',
number: 1,
label: Label::LABEL_OPTIONAL,
type: Type::TYPE_MESSAGE,
typeName: '.t.M.Inner',
oneofIndex: $oneofIndex,
jsonName: 'd',
options: new FieldOptions(
features: new FeatureSet(messageEncoding: FeatureSet\MessageEncoding::DELIMITED),
),
),
],
nestedType: [
new DescriptorProto(
name: 'Inner',
field: [
new FieldDescriptorProto(
name: 'a',
number: 1,
label: Label::LABEL_OPTIONAL,
type: Type::TYPE_INT32,
jsonName: 'a',
),
],
),
],
oneofDecl: $oneofIndex !== null ? [new OneofDescriptorProto('o')] : [],
),
],
syntax: 'editions',
edition: Edition::EDITION_2023,
),
],
));
}
}
93 changes: 93 additions & 0 deletions tests/GeneratedCode/samples/oneof_variants.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

declare(strict_types=1);

/**
* Samples of the oneof_variants snapshot case, keyed by label (see GeneratedCodeTest): every variant built with its
* default value, which is written as the variant is set, and a check of the defaults the variants are declared with.
*/

use BcMath\Number;
use Oneof\Variants\Editions;
use Oneof\Variants\Proto2;

$samples = [];

foreach ([
Proto2\Choice\ValueNumber::class,
Proto2\Choice\ValueText::class,
Proto2\Choice\ValueRaw::class,
Proto2\Choice\ValueFlag::class,
Proto2\Choice\ValueBig::class,
Proto2\Choice\ValueRatio::class,
Proto2\Choice\ValueLevel::class,
] as $variant) {
$samples["proto2 variant {$variant} with its default value"] = new Proto2\Choice(value: new $variant());
}

foreach ([
Proto2\Choice\DefaultedNumberDefault::class,
Proto2\Choice\DefaultedTextDefault::class,
Proto2\Choice\DefaultedRawDefault::class,
Proto2\Choice\DefaultedRatioDefault::class,
Proto2\Choice\DefaultedLevelDefault::class,
] as $variant) {
$samples["proto2 variant {$variant} with its declared default"] = new Proto2\Choice(defaulted: new $variant());
}

foreach ([
Editions\Choice\ValueNumber::class,
Editions\Choice\ValueText::class,
Editions\Choice\ValueLevel::class,
] as $variant) {
$samples["editions variant {$variant} with its default value"] = new Editions\Choice(value: new $variant());
}

foreach ([
Editions\Choice\DefaultedNumberDefault::class,
Editions\Choice\DefaultedTextDefault::class,
Editions\Choice\DefaultedLevelDefault::class,
] as $variant) {
$samples["editions variant {$variant} with its declared default"] = new Editions\Choice(defaulted: new $variant());
}

return [
...$samples,
'proto2 variants set' => new Proto2\Choice(
value: new Proto2\Choice\ValueInner(new Proto2\Inner(7)),
defaulted: new Proto2\Choice\DefaultedLevelDefault(Proto2\Level::LEVEL_LOW),
),
'proto2 uint64 variant set' => new Proto2\Choice(value: new Proto2\Choice\ValueBig(new Number('18446744073709551615'))),
'editions variants set' => new Editions\Choice(
value: new Editions\Choice\ValueInner(new Editions\Inner(-1)),
defaulted: new Editions\Choice\DefaultedNumberDefault(0),
),
'variants take the declared defaults' => static function (): void {
$expected = [
'proto2 number' => [new Proto2\Choice\ValueNumber()->number, 0],
'proto2 level' => [new Proto2\Choice\ValueLevel()->level, Proto2\Level::LEVEL_LOW],
'proto2 numberDefault' => [new Proto2\Choice\DefaultedNumberDefault()->numberDefault, 42],
'proto2 textDefault' => [new Proto2\Choice\DefaultedTextDefault()->textDefault, 'hello'],
'proto2 rawDefault' => [new Proto2\Choice\DefaultedRawDefault()->rawDefault, "\x01\xff"],
'proto2 ratioDefault' => [new Proto2\Choice\DefaultedRatioDefault()->ratioDefault, INF],
'proto2 levelDefault' => [new Proto2\Choice\DefaultedLevelDefault()->levelDefault, Proto2\Level::LEVEL_HIGH],
'editions numberDefault' => [new Editions\Choice\DefaultedNumberDefault()->numberDefault, 42],
'editions textDefault' => [new Editions\Choice\DefaultedTextDefault()->textDefault, 'hello'],
'editions levelDefault' => [new Editions\Choice\DefaultedLevelDefault()->levelDefault, Editions\Level::LEVEL_HIGH],
];

// Bytes are printed escaped, the failure is reported as JSON.
$show = static fn(mixed $value): string => is_string($value) ? '"' . addcslashes($value, "\0..\37\"\\\177..\377") . '"' : var_export($value, true);
$mismatches = [];

foreach ($expected as $variant => [$actual, $value]) {
if ($actual !== $value) {
$mismatches[] = sprintf('%s: expected %s, got %s', $variant, $show($value), $show($actual));
}
}

if ($mismatches !== []) {
throw new LogicException(implode('; ', $mismatches) . '.');
}
},
];
30 changes: 30 additions & 0 deletions tests/fixtures/oneof_variants/editions.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
edition = "2023";

package oneof.variants.editions;

enum Level {
LEVEL_UNSPECIFIED = 0;
LEVEL_HIGH = 1;
}

message Inner {
int32 value = 1;
}

// Oneof fields have explicit presence, yet a variant is not nullable: its class exists
// only once the oneof is set to it. A message variant stays nullable, as everywhere.
message Choice {
oneof value {
int32 number = 1;
string text = 2;
Level level = 3;
Inner inner = 4;
}

// The declared default becomes the default of the variant.
oneof defaulted {
int32 number_default = 11 [default = 42];
string text_default = 12 [default = "hello"];
Level level_default = 13 [default = LEVEL_HIGH];
}
}
37 changes: 37 additions & 0 deletions tests/fixtures/oneof_variants/proto2.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
syntax = "proto2";

package oneof.variants.proto2;

// A closed enum without a zero value: the default of a variant is its first value.
enum Level {
LEVEL_LOW = 1;
LEVEL_HIGH = 2;
}

message Inner {
optional int32 value = 1;
}

// A variant class exists only once the oneof is set to it, so its field is not nullable,
// the same as in proto3 and editions. A message variant stays nullable, as everywhere.
message Choice {
oneof value {
int32 number = 1;
string text = 2;
bytes raw = 3;
bool flag = 4;
uint64 big = 5;
double ratio = 6;
Level level = 7;
Inner inner = 8;
}

// The declared default becomes the default of the variant.
oneof defaulted {
int32 number_default = 11 [default = 42];
string text_default = 12 [default = "hello"];
bytes raw_default = 13 [default = "\001\377"];
double ratio_default = 14 [default = inf];
Level level_default = 15 [default = LEVEL_HIGH];
}
}
40 changes: 40 additions & 0 deletions tests/snapshots/oneof_variants/Oneof/Variants/Editions/Choice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/**
* Code generated by thesis/protoc-plugin. DO NOT EDIT.
* Versions:
* thesis/protoc-plugin — v0.6.x-dev
* protoc — v6.32.1
* Source: editions.proto
*/

declare(strict_types=1);

namespace Oneof\Variants\Editions;

use Thesis\Protobuf\Reflection;

/**
* @api
*
* Oneof fields have explicit presence, yet a variant is not nullable: its class exists
* only once the oneof is set to it. A message variant stays nullable, as everywhere.
*/
final readonly class Choice
{
public function __construct(
#[Reflection\OneOf([
\Oneof\Variants\Editions\Choice\ValueNumber::class,
\Oneof\Variants\Editions\Choice\ValueText::class,
\Oneof\Variants\Editions\Choice\ValueLevel::class,
\Oneof\Variants\Editions\Choice\ValueInner::class,
])]
public ?\Oneof\Variants\Editions\Choice\Value $value = null,
#[Reflection\OneOf([
\Oneof\Variants\Editions\Choice\DefaultedNumberDefault::class,
\Oneof\Variants\Editions\Choice\DefaultedTextDefault::class,
\Oneof\Variants\Editions\Choice\DefaultedLevelDefault::class,
])]
public ?\Oneof\Variants\Editions\Choice\Defaulted $defaulted = null,
) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

/**
* Code generated by thesis/protoc-plugin. DO NOT EDIT.
* Versions:
* thesis/protoc-plugin — v0.6.x-dev
* protoc — v6.32.1
* Source: editions.proto
*/

declare(strict_types=1);

namespace Oneof\Variants\Editions\Choice;

/**
* @api
* @phpstan-sealed (
* DefaultedNumberDefault |
* DefaultedTextDefault |
* DefaultedLevelDefault
* )
*/
interface Defaulted {}
Loading