diff --git a/src/Plugin/Generator/ProtoGenerator.php b/src/Plugin/Generator/ProtoGenerator.php index cbd8b6c..52442f4 100644 --- a/src/Plugin/Generator/ProtoGenerator.php +++ b/src/Plugin/Generator/ProtoGenerator.php @@ -277,6 +277,7 @@ private static function claimClassName(array &$owners, Parser\MessageDescriptor /** * @param list $implements * @param array $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( @@ -285,6 +286,7 @@ private function generateMessage( Parser\MessageDescriptor $message, array $implements = [], array $oneofInterfaces = [], + bool $oneofVariant = false, ): PhpNamespace { $classType = new ClassType($className) ->setFinal() @@ -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); @@ -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, @@ -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, ), ], @@ -589,6 +598,7 @@ private function generateOneofVariant( [ $this->namespacer->fqcn("{$message->path}.{$interfaceName}"), ], + oneofVariant: true, ); } diff --git a/tests/CompilerOneofVariantTest.php b/tests/CompilerOneofVariantTest.php new file mode 100644 index 0000000..9da1c86 --- /dev/null +++ b/tests/CompilerOneofVariantTest.php @@ -0,0 +1,104 @@ +expectException(CodeCannotBeGenerated::class); + $this->expectExceptionMessage('DELIMITED message encoding are not supported'); + + self::compile($oneofIndex); + } + + /** + * @return iterable + */ + 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, + ), + ], + )); + } +} diff --git a/tests/GeneratedCode/samples/oneof_variants.php b/tests/GeneratedCode/samples/oneof_variants.php new file mode 100644 index 0000000..5d44a62 --- /dev/null +++ b/tests/GeneratedCode/samples/oneof_variants.php @@ -0,0 +1,93 @@ + 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) . '.'); + } + }, +]; diff --git a/tests/fixtures/oneof_variants/editions.proto b/tests/fixtures/oneof_variants/editions.proto new file mode 100644 index 0000000..29dfd0b --- /dev/null +++ b/tests/fixtures/oneof_variants/editions.proto @@ -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]; + } +} diff --git a/tests/fixtures/oneof_variants/proto2.proto b/tests/fixtures/oneof_variants/proto2.proto new file mode 100644 index 0000000..809fa37 --- /dev/null +++ b/tests/fixtures/oneof_variants/proto2.proto @@ -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]; + } +} diff --git a/tests/snapshots/oneof_variants/Oneof/Variants/Editions/Choice.php b/tests/snapshots/oneof_variants/Oneof/Variants/Editions/Choice.php new file mode 100644 index 0000000..a7c1d96 --- /dev/null +++ b/tests/snapshots/oneof_variants/Oneof/Variants/Editions/Choice.php @@ -0,0 +1,40 @@ +add(Registry\Descriptor::base64(self::EDITIONS_DESCRIPTOR_BUFFER), new File( + name: 'editions.proto', + messages: [ + new File\MessageDescriptor('oneof.variants.editions.Inner', \Oneof\Variants\Editions\Inner::class), + new File\MessageDescriptor('oneof.variants.editions.Choice', \Oneof\Variants\Editions\Choice::class), + ], + enums: [ + new File\EnumDescriptor('oneof.variants.editions.Level', \Oneof\Variants\Editions\Level::class), + ], + )); + } +} diff --git a/tests/snapshots/oneof_variants/Oneof/Variants/Editions/Inner.php b/tests/snapshots/oneof_variants/Oneof/Variants/Editions/Inner.php new file mode 100644 index 0000000..002ae5a --- /dev/null +++ b/tests/snapshots/oneof_variants/Oneof/Variants/Editions/Inner.php @@ -0,0 +1,26 @@ +add(Registry\Descriptor::base64(self::PROTO2_DESCRIPTOR_BUFFER), new File( + name: 'proto2.proto', + messages: [ + new File\MessageDescriptor('oneof.variants.proto2.Inner', \Oneof\Variants\Proto2\Inner::class), + new File\MessageDescriptor('oneof.variants.proto2.Choice', \Oneof\Variants\Proto2\Choice::class), + ], + enums: [ + new File\EnumDescriptor('oneof.variants.proto2.Level', \Oneof\Variants\Proto2\Level::class), + ], + )); + } +} diff --git a/tests/snapshots/oneof_variants/Oneof/Variants/Proto2/Inner.php b/tests/snapshots/oneof_variants/Oneof/Variants/Proto2/Inner.php new file mode 100644 index 0000000..12f99ac --- /dev/null +++ b/tests/snapshots/oneof_variants/Oneof/Variants/Proto2/Inner.php @@ -0,0 +1,26 @@ +register( + new \Thesis\Protobuf\Registry\OnceRegistrar(new \Oneof\Variants\Editions\DescriptorRegistry()), + new \Thesis\Protobuf\Registry\OnceRegistrar(new \Oneof\Variants\Proto2\DescriptorRegistry()), +); diff --git a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/Nested/Deep/UnionEmail.php b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/Nested/Deep/UnionEmail.php index 22a4637..094c02f 100644 --- a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/Nested/Deep/UnionEmail.php +++ b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/Nested/Deep/UnionEmail.php @@ -21,6 +21,6 @@ { public function __construct( #[Reflection\Field(3, Reflection\StringT::T)] - public ?string $email = null, + public string $email = '', ) {} } diff --git a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/Nested/Deep/UnionPhone.php b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/Nested/Deep/UnionPhone.php index 5eb47f3..4c6762c 100644 --- a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/Nested/Deep/UnionPhone.php +++ b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/Nested/Deep/UnionPhone.php @@ -21,6 +21,6 @@ { public function __construct( #[Reflection\Field(2, Reflection\StringT::T)] - public ?string $phone = null, + public string $phone = '', ) {} } diff --git a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldData.php b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldData.php index 677bd67..c1f11a6 100644 --- a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldData.php +++ b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldData.php @@ -21,6 +21,6 @@ { public function __construct( #[Reflection\Field(7, Reflection\BytesT::T)] - public ?string $data = null, + public string $data = '', ) {} } diff --git a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldDeepEnum.php b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldDeepEnum.php index 5410ca6..68016a0 100644 --- a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldDeepEnum.php +++ b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldDeepEnum.php @@ -21,6 +21,6 @@ { public function __construct( #[Reflection\Field(4, new Reflection\EnumT(\Proto\Api\V1\TestRequest\Nested\Deep\DeepEnum::class))] - public ?\Proto\Api\V1\TestRequest\Nested\Deep\DeepEnum $deepEnum = null, + public \Proto\Api\V1\TestRequest\Nested\Deep\DeepEnum $deepEnum = \Proto\Api\V1\TestRequest\Nested\Deep\DeepEnum::DEEP_ENUM_UNSPECIFIED, ) {} } diff --git a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldName.php b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldName.php index 9b06c12..b41c96a 100644 --- a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldName.php +++ b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldName.php @@ -21,6 +21,6 @@ { public function __construct( #[Reflection\Field(6, Reflection\StringT::T)] - public ?string $name = null, + public string $name = '', ) {} } diff --git a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldNumber.php b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldNumber.php index 4490bc5..db817d4 100644 --- a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldNumber.php +++ b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldNumber.php @@ -21,6 +21,6 @@ { public function __construct( #[Reflection\Field(5, Reflection\Int32T::T)] - public ?int $number = null, + public int $number = 0, ) {} } diff --git a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldTempC.php b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldTempC.php index 3f89d6c..695073d 100644 --- a/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldTempC.php +++ b/tests/snapshots/proto2/Proto/Api/V1/TestRequest/XFieldTempC.php @@ -21,6 +21,6 @@ { public function __construct( #[Reflection\Field(8, Reflection\DoubleT::T)] - public ?float $tempC = null, + public float $tempC = 0, ) {} }