diff --git a/README.md b/README.md index 02c5a9f..9ef8e80 100644 --- a/README.md +++ b/README.md @@ -511,19 +511,22 @@ The PHP default of a constructor parameter follows from field presence and wheth **proto2** -| protobuf | php | -|-------------------------------------------|--------------------------------------------------------| -| `required int32 x = 1;` | `int $x` | -| `required uint64 x = 1;` | `\BcMath\Number $x` | -| `required string x = 1 [default = "hi"];` | `string $x = 'hi'` | -| `required Foo x = 1 [default = FOO_BAR];` | `Foo $x = Foo::FOO_BAR` | -| `required Msg x = 1;` | `Msg $x` | -| `optional int32 x = 1;` | `?int $x = null` | -| `optional int32 x = 1 [default = 5];` | `?int $x = null` | -| `optional Foo x = 1 [default = FOO_BAR];` | `Foo $x = Foo::FOO_BAR` | -| `optional Msg x = 1;` | `?Msg $x = null` | -| `repeated int32 x = 1;` | `array $x = []` | -| `map x = 1;` | `\Thesis\Protobuf\Map $x = new \Thesis\Protobuf\Map()` | +| protobuf | php | +|-----------------------------------------------------------|------------------------------------------------------------------| +| `required int32 x = 1;` | `int $x` | +| `required uint64 x = 1;` | `\BcMath\Number $x` | +| `required string x = 1 [default = "hi"];` | `string $x = 'hi'` | +| `required Foo x = 1 [default = FOO_BAR];` | `Foo $x = Foo::FOO_BAR` | +| `required double x = 1 [default = inf];` | `float $x = \INF` (`-inf` → `-\INF`, `nan` → `\NAN`) | +| `required uint64 x = 1 [default = 18446744073709551615];` | `\BcMath\Number $x = new \BcMath\Number('18446744073709551615')` | +| `required bytes x = 1 [default = "\001\377"];` | `string $x = "\x01\xFF"` | +| `required Msg x = 1;` | `Msg $x` | +| `optional int32 x = 1;` | `?int $x = null` | +| `optional int32 x = 1 [default = 5];` | `?int $x = null` | +| `optional Foo x = 1 [default = FOO_BAR];` | `Foo $x = Foo::FOO_BAR` | +| `optional Msg x = 1;` | `?Msg $x = null` | +| `repeated int32 x = 1;` | `array $x = []` | +| `map x = 1;` | `\Thesis\Protobuf\Map $x = new \Thesis\Protobuf\Map()` | **proto3** diff --git a/src/Plugin/Generator/ProtoGenerator.php b/src/Plugin/Generator/ProtoGenerator.php index f9dc54b..e0d3a5f 100644 --- a/src/Plugin/Generator/ProtoGenerator.php +++ b/src/Plugin/Generator/ProtoGenerator.php @@ -390,11 +390,7 @@ private function generateMessage( // is non-nullable. For nullable fields we keep `null` so that presence // round-trips: the user can distinguish "field unset" from "field set to its proto default". if (!$nullable && $field->defaultValue !== null && $field->type !== null) { - $default = $this->parseDefaultValue( - $field->type, - $field->defaultValue, - $field->typeName, - ); + $default = $this->parseDefaultValue($message, $field, $field->type, $field->defaultValue); } $parameter @@ -566,37 +562,180 @@ private function generateOneofVariant( ); } + /** + * Turns FieldDescriptorProto.default_value into the PHP default of the constructor parameter. The value comes + * as text: numbers as written in the schema (floats may be inf, -inf, nan), bools as true/false, strings as is, + * bytes C-escaped, enums as the name of the value. + * + * @throws CodeCannotBeGenerated + */ private function parseDefaultValue( + Parser\MessageDescriptor $message, + Parser\FieldDescriptor $field, FieldDescriptorProto\Type $type, string $defaultValue, - ?string $typename = null, ): mixed { - if ($type === FieldDescriptorProto\Type::TYPE_ENUM && $typename !== null) { - // Resolved through the graph, so that a relocated enum is referenced - // under the very namespace it is generated into. - return new Literal(\sprintf("%s::{$defaultValue}", $this->graph->get($typename)->fqcn)); - } - - return match ($type) { - FieldDescriptorProto\Type::TYPE_STRING, - FieldDescriptorProto\Type::TYPE_BYTES => $defaultValue, + $value = match ($type) { + FieldDescriptorProto\Type::TYPE_ENUM => $this->enumDefault($field, $defaultValue), + FieldDescriptorProto\Type::TYPE_STRING => $defaultValue, + FieldDescriptorProto\Type::TYPE_BYTES => self::unescapeBytes($defaultValue), FieldDescriptorProto\Type::TYPE_INT32, FieldDescriptorProto\Type::TYPE_SINT32, + FieldDescriptorProto\Type::TYPE_SFIXED32 => self::integerDefault($defaultValue, -2_147_483_648, 2_147_483_647), FieldDescriptorProto\Type::TYPE_UINT32, - FieldDescriptorProto\Type::TYPE_FIXED32, - FieldDescriptorProto\Type::TYPE_SFIXED32, + FieldDescriptorProto\Type::TYPE_FIXED32 => self::integerDefault($defaultValue, 0, 4_294_967_295), + // var_export(), and so Nette, prints PHP_INT_MIN as -9223372036854775807-1: the literal + // -9223372036854775808 would be a float. FieldDescriptorProto\Type::TYPE_INT64, FieldDescriptorProto\Type::TYPE_SINT64, - FieldDescriptorProto\Type::TYPE_SFIXED64 => filter_var($defaultValue, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE) ?? 0, + FieldDescriptorProto\Type::TYPE_SFIXED64 => self::integerDefault($defaultValue, PHP_INT_MIN, PHP_INT_MAX), FieldDescriptorProto\Type::TYPE_UINT64, - FieldDescriptorProto\Type::TYPE_FIXED64 => Literal::new('\BcMath\Number', [ - filter_var($defaultValue, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE) ?? 0, - ]), - FieldDescriptorProto\Type::TYPE_BOOL => filter_var($defaultValue, FILTER_VALIDATE_BOOLEAN), - FieldDescriptorProto\Type::TYPE_FLOAT, - FieldDescriptorProto\Type::TYPE_DOUBLE => filter_var($defaultValue, FILTER_VALIDATE_FLOAT), + FieldDescriptorProto\Type::TYPE_FIXED64 => self::unsignedInteger64Default($defaultValue), + FieldDescriptorProto\Type::TYPE_BOOL => match ($defaultValue) { + 'true' => true, + 'false' => false, + default => null, + }, + FieldDescriptorProto\Type::TYPE_FLOAT => self::floatDefault($defaultValue, single: true), + FieldDescriptorProto\Type::TYPE_DOUBLE => self::floatDefault($defaultValue, single: false), + default => null, + }; + + return $value ?? throw new CodeCannotBeGenerated(\sprintf( + 'Message %s: field %s has the default value "%s" that is not valid for %s.', + $message->fqcn, + $field->name, + addcslashes($defaultValue, "\0..\37\"\\\177..\377"), + $type->name, + )); + } + + private function enumDefault(Parser\FieldDescriptor $field, string $defaultValue): ?Literal + { + if ($field->typeName === null) { + return null; + } + + // Resolved through the graph, so that a relocated enum is referenced + // under the very namespace it is generated into. + $enum = $this->graph->get($field->typeName); + + if (!$enum->container instanceof Parser\EnumDescriptor) { + return null; + } + + foreach ($enum->container->cases as $case) { + // Every value has a member of the generated enum under its secured name: a case, a constant of an alias, + // or, for a value dropped by generateEnum() as a duplicate of that name, the member it duplicates. + if ($case->name === $defaultValue) { + return new Literal(\sprintf('%s::%s', $enum->fqcn, Naming::secureEnumCase($case->name))); + } + } + + return null; + } + + private static function integerDefault(string $value, int $min, int $max): ?int + { + if (preg_match('/^-?(?:0|[1-9][0-9]*)$/D', $value) !== 1) { + return null; + } + + $integer = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]]); + + return \is_int($integer) ? $integer : null; + } + + /** + * new \BcMath\Number(int) for values that fit PHP int, so that the output of the usual ones is unchanged, + * and new \BcMath\Number(string) beyond PHP_INT_MAX. + */ + private static function unsignedInteger64Default(string $value): ?Literal + { + if (preg_match('/^(?:0|[1-9][0-9]*)$/D', $value) !== 1) { + return null; + } + + $integer = filter_var($value, FILTER_VALIDATE_INT); + + if (\is_int($integer)) { + return Literal::new('\BcMath\Number', [$integer]); + } + + // Without leading zeros, a longer number is a greater one. + $max = '18446744073709551615'; + + if (\strlen($value) > \strlen($max) || (\strlen($value) === \strlen($max) && strcmp($value, $max) > 0)) { + return null; + } + + return Literal::new('\BcMath\Number', [$value]); + } + + /** + * @param bool $single whether the field is a 32-bit float: protoc gives its default with the precision of float, + * the value is rounded to float, so that the PHP default is the one the field holds on the wire + */ + private static function floatDefault(string $value, bool $single): null|float|Literal + { + $special = match (strtolower($value)) { + 'inf', '+inf', 'infinity', '+infinity' => '\INF', + '-inf', '-infinity' => '-\INF', + 'nan', '+nan', '-nan' => '\NAN', default => null, }; + + if ($special !== null) { + return new Literal($special); + } + + if (preg_match('/^[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/D', $value) !== 1) { + return null; + } + + $float = filter_var($value, FILTER_VALIDATE_FLOAT); + + if ($single && \is_float($float)) { + $float = unpack('g', pack('g', $float))[1] ?? null; + } + + return \is_float($float) && is_finite($float) ? $float : null; + } + + /** + * Decodes the C-escaped value protoc gives for bytes: octal \NNN (every byte >= 0x80 and other + * non-printable ones), \n, \r, \t, \", \', \\; also the rest of the C escapes and hex \xHH. + */ + private static function unescapeBytes(string $value): ?string + { + $simple = ['n' => "\n", 'r' => "\r", 't' => "\t", 'a' => "\x07", 'b' => "\x08", 'f' => "\f", 'v' => "\v", '\\' => '\\', "'" => "'", '"' => '"', '?' => '?']; + + $valid = true; + + $bytes = preg_replace_callback( + '/\\\(?:([0-7]{1,3})|[xX]([0-9a-fA-F]{1,2})|(.)|$)/sD', + static function (array $matches) use ($simple, &$valid): string { + if ($matches[1] !== null && ($code = octdec($matches[1])) <= 0xFF) { + return \chr((int) $code); + } + + if ($matches[2] !== null) { + return \chr((int) hexdec($matches[2])); + } + + if ($matches[3] !== null && isset($simple[$matches[3]])) { + return $simple[$matches[3]]; + } + + $valid = false; + + return $matches[0]; + }, + $value, + flags: PREG_UNMATCHED_AS_NULL, + ); + + return $valid ? $bytes : null; } private static function oneofVariantName(string $oneof, Parser\FieldDescriptor $variant): string diff --git a/tests/CompilerDefaultValueTest.php b/tests/CompilerDefaultValueTest.php new file mode 100644 index 0000000..37e6ae3 --- /dev/null +++ b/tests/CompilerDefaultValueTest.php @@ -0,0 +1,131 @@ +expectException(CodeCannotBeGenerated::class); + $this->expectExceptionMessage("Message t.M: field f has the default value \"{$error}\" that is not valid for {$type->name}."); + + self::compile($type, $default); + } + + /** + * @return iterable + */ + public static function provideInvalidDefaultIsReportedCases(): iterable + { + yield 'double, not a number' => [Type::TYPE_DOUBLE, 'abc', 'abc']; + yield 'double, empty' => [Type::TYPE_DOUBLE, '', '']; + yield 'double, surrounded by spaces' => [Type::TYPE_DOUBLE, ' 1.5', ' 1.5']; + yield 'double, out of range' => [Type::TYPE_DOUBLE, '1e400', '1e400']; + yield 'float, out of range' => [Type::TYPE_FLOAT, '1e39', '1e39']; + yield 'int32, fraction' => [Type::TYPE_INT32, '1.5', '1.5']; + yield 'int32, above the maximum' => [Type::TYPE_INT32, '2147483648', '2147483648']; + yield 'sint32, below the minimum' => [Type::TYPE_SINT32, '-2147483649', '-2147483649']; + yield 'uint32, negative' => [Type::TYPE_UINT32, '-1', '-1']; + yield 'fixed32, above the maximum' => [Type::TYPE_FIXED32, '4294967296', '4294967296']; + yield 'int64, above the maximum' => [Type::TYPE_INT64, '9223372036854775808', '9223372036854775808']; + yield 'sfixed64, below the minimum' => [Type::TYPE_SFIXED64, '-9223372036854775809', '-9223372036854775809']; + yield 'int64, hexadecimal' => [Type::TYPE_INT64, '0x10', '0x10']; + yield 'uint64, negative' => [Type::TYPE_UINT64, '-1', '-1']; + yield 'fixed64, above the maximum' => [Type::TYPE_FIXED64, '18446744073709551616', '18446744073709551616']; + yield 'bool, not true or false' => [Type::TYPE_BOOL, 'yes', 'yes']; + yield 'bytes, unknown escape' => [Type::TYPE_BYTES, 'a\q', 'a\\\q']; + yield 'bytes, trailing backslash' => [Type::TYPE_BYTES, 'a\\', 'a\\\\']; + yield 'bytes, octal above a byte' => [Type::TYPE_BYTES, '\400', '\\\400']; + yield 'bytes, hex without digits' => [Type::TYPE_BYTES, '\xg', '\\\xg']; + yield 'enum, no such value' => [Type::TYPE_ENUM, 'C', 'C']; + yield 'enum, secured name instead of the value' => [Type::TYPE_ENUM, 'class_', 'class_']; + yield 'message' => [Type::TYPE_MESSAGE, 'x', 'x']; + } + + /** + * protoc escapes bytes with octal \NNN, \n, \r, \t, \", \', \\ only; the rest of the C escapes are decoded too. + */ + public function testOtherCEscapesOfBytesAreDecoded(): void + { + $content = ''; + + foreach (self::compile(Type::TYPE_BYTES, '\x41\x7\a\b\f\v\?\0\12') as $file) { + if ($file->name === 'T/M.php') { + $content = (string) $file->content; + } + } + + self::assertStringContainsString('public string $f = "A\x07\x07\x08\x0C\x0B?\x00\n",', $content); + } + + /** + * @return list + * @throws ProtocException + */ + private static function compile(Type $type, string $default): array + { + $request = new CodeGeneratorRequest( + fileToGenerate: ['t.proto'], + protoFile: [ + new FileDescriptorProto( + name: 't.proto', + package: 't', + messageType: [ + new DescriptorProto( + name: 'M', + field: [ + new FieldDescriptorProto( + name: 'f', + number: 1, + label: FieldDescriptorProto\Label::LABEL_REQUIRED, + type: $type, + typeName: match ($type) { + Type::TYPE_ENUM => '.t.E', + Type::TYPE_MESSAGE => '.t.M', + default => null, + }, + defaultValue: $default, + jsonName: 'f', + ), + ], + ), + ], + enumType: [ + new EnumDescriptorProto( + name: 'E', + value: [new EnumValueDescriptorProto('class', 0), new EnumValueDescriptorProto('B', 1)], + ), + ], + ), + ], + ); + + return new Compiler(Encoder\Builder::buildDefault(), __DIR__ . '/../map.json')->compile($request); + } +} diff --git a/tests/GeneratedCode/GeneratedCodeTest.php b/tests/GeneratedCode/GeneratedCodeTest.php index b5db321..f016bcc 100644 --- a/tests/GeneratedCode/GeneratedCodeTest.php +++ b/tests/GeneratedCode/GeneratedCodeTest.php @@ -15,7 +15,8 @@ * 2. every class, interface and enum loads, enums give their cases, messages without required constructor * parameters are instantiated, autoload.metadata.php registers every DescriptorRegistry in the pool; * 3. messages survive an encode/decode round-trip through thesis/protobuf: the instantiated ones and the - * populated samples from samples/.php. + * populated samples from samples/.php. A sample may also be a closure, a check of values of the + * generated code (e.g. the defaults a message is created with), which throws on a mismatch. * * Each case runs in its own PHP process (see SnapshotValidator): cases declare classes with the same names, * and a broken snapshot may end the process with a fatal error. diff --git a/tests/GeneratedCode/SnapshotValidator.php b/tests/GeneratedCode/SnapshotValidator.php index 505f845..5f54a1e 100644 --- a/tests/GeneratedCode/SnapshotValidator.php +++ b/tests/GeneratedCode/SnapshotValidator.php @@ -131,12 +131,21 @@ private function run(): int $objects = require $samples; if (!\is_array($objects) || $objects === []) { - throw new \LogicException('The samples file must return a non-empty array of messages keyed by label.'); + throw new \LogicException('The samples file must return a non-empty array of messages (or checks) keyed by label.'); } foreach ($objects as $label => $object) { if (!\is_string($label) || !\is_object($object)) { - throw new \LogicException("Sample {$label} must be a message keyed by a string label."); + throw new \LogicException("Sample {$label} must be a message (or a check) keyed by a string label."); + } + + // A check inspects values of the generated code, e.g. the defaults of a message, and throws on a mismatch. + if ($object instanceof \Closure) { + $this->attempt("check sample '{$label}'", static function () use ($object): void { + $object(); + }); + + continue; } $this->attempt("round-trip sample '{$label}'", fn() => $this->roundTrip($object)); @@ -337,7 +346,7 @@ private function roundTrip(object $message): void } /** - * Strict structural comparison: unlike ==, it tells null from '' and 0, and 1 from 1.0. + * Strict structural comparison: unlike ==, it tells null from '' and 0, and 1 from 1.0; only NaN equals NaN. */ private static function difference(mixed $expected, mixed $actual, string $path): ?string { @@ -387,6 +396,11 @@ private static function difference(mixed $expected, mixed $actual, string $path) return null; } + // NAN !== NAN, yet a NaN that came back as a NaN is the same value. + if (\is_float($expected) && \is_float($actual) && is_nan($expected) && is_nan($actual)) { + return null; + } + return $expected === $actual ? null : "{$path}: expected " . get_debug_type($expected) . ' ' . var_export($expected, true) . ', got ' . get_debug_type($actual) . ' ' . var_export($actual, true); } diff --git a/tests/GeneratedCode/samples/field_defaults.php b/tests/GeneratedCode/samples/field_defaults.php new file mode 100644 index 0000000..09b90c2 --- /dev/null +++ b/tests/GeneratedCode/samples/field_defaults.php @@ -0,0 +1,112 @@ + $values property => [actual, expected], compared with === + */ +$expect = static function (array $values): void { + foreach ($values as $property => [$actual, $expected]) { + if ($actual instanceof Number) { + $actual = (string) $actual; + } + + if ($actual !== $expected) { + throw new LogicException(sprintf('%s: expected %s, got %s', $property, var_export($expected, true), var_export($actual, true))); + } + } +}; + +return [ + 'proto2 defaults' => static function () use ($expect): void { + $message = new Defaults(); + + $expect([ + 'doubleInf is +INF' => [is_infinite($message->doubleInf) && $message->doubleInf > 0, true], + 'doubleNegInf is -INF' => [is_infinite($message->doubleNegInf) && $message->doubleNegInf < 0, true], + 'doubleNan is NAN' => [is_nan($message->doubleNan), true], + 'floatInf is +INF' => [is_infinite($message->floatInf) && $message->floatInf > 0, true], + 'floatNegInf is -INF' => [is_infinite($message->floatNegInf) && $message->floatNegInf < 0, true], + 'floatNan is NAN' => [is_nan($message->floatNan), true], + 'doubleExponent' => [$message->doubleExponent, 1.5e300], + 'floatExponent' => [$message->floatExponent, -2 ** -13], + 'doubleIntegral' => [$message->doubleIntegral, 42.0], + 'doubleMax' => [$message->doubleMax, PHP_FLOAT_MAX], + 'floatFraction' => [$message->floatFraction, 314_159.0], + 'uint64Max' => [$message->uint64Max, '18446744073709551615'], + 'fixed64Max' => [$message->fixed64Max, '18446744073709551615'], + 'uint64AboveInt' => [$message->uint64AboveInt, '9223372036854775808'], + 'uint64IntMax' => [$message->uint64IntMax, '9223372036854775807'], + 'fixed64Small' => [$message->fixed64Small, '6400'], + 'int64Min' => [$message->int64Min, PHP_INT_MIN], + 'int64Max' => [$message->int64Max, PHP_INT_MAX], + 'sint64Min' => [$message->sint64Min, PHP_INT_MIN], + 'sfixed64Min' => [$message->sfixed64Min, PHP_INT_MIN], + 'sfixed64Max' => [$message->sfixed64Max, PHP_INT_MAX], + 'int32Min' => [$message->int32Min, -(2 ** 31)], + 'int32Max' => [$message->int32Max, 2 ** 31 - 1], + 'sint32Min' => [$message->sint32Min, -(2 ** 31)], + 'sfixed32Min' => [$message->sfixed32Min, -(2 ** 31)], + 'uint32Max' => [$message->uint32Max, 2 ** 32 - 1], + 'fixed32Max' => [$message->fixed32Max, 2 ** 32 - 1], + 'boolTrue' => [$message->boolTrue, true], + 'bytesOctal' => [bin2hex($message->bytesOctal), '0102ff'], + // q " u o t e ' \ b a c k NUL n u l 0x80 0xFE LF CR TAB $ x + 'bytesSpecial' => [bin2hex($message->bytesSpecial), '7122756f7465275c6261636b006e756c80fe0a0d092478'], + 'stringPhp' => [$message->stringPhp, '$var {$x} \ "q" \'a\' ' . "\n"], + 'stringEscapeLike' => [bin2hex($message->stringEscapeLike), '615c30303162'], + 'stringUnicode' => [$message->stringUnicode, 'привет'], + 'keywordReserved' => [$message->keywordReserved, Keyword::class_], + 'keywordDropped' => [$message->keywordDropped, Keyword::class_], + 'keywordAlias' => [$message->keywordAlias, Keyword::other], + ]); + + $bytes = Encoder\Builder::buildDefault()->encode($message); + + $expect([ + // tag 20 (varint), 2^64 - 1 + 'uint64Max on the wire' => [str_contains($bytes, "\xA0\x01" . str_repeat("\xFF", 9) . "\x01"), true], + // tag 21 (fixed64), 2^64 - 1 + 'fixed64Max on the wire' => [str_contains($bytes, "\xA9\x01" . str_repeat("\xFF", 8)), true], + // tag 22 (varint), 2^63 + 'uint64AboveInt on the wire' => [str_contains($bytes, "\xB0\x01" . str_repeat("\x80", 9) . "\x01"), true], + // tag 30 (varint), -2^63 + 'int64Min on the wire' => [str_contains($bytes, "\xF0\x01" . str_repeat("\x80", 9) . "\x01"), true], + // tag 61 (length-delimited), 23 bytes + 'bytesSpecial on the wire' => [str_contains($bytes, "\xEA\x03\x17" . $message->bytesSpecial), true], + ]); + }, + 'editions defaults' => static function () use ($expect): void { + $message = new EditionDefaults(); + + $expect([ + 'doubleNan is NAN' => [is_nan($message->doubleNan), true], + 'floatNegInf is -INF' => [is_infinite($message->floatNegInf) && $message->floatNegInf < 0, true], + 'uint64Max' => [$message->uint64Max, '18446744073709551615'], + 'int64Min' => [$message->int64Min, PHP_INT_MIN], + 'bytesEscaped' => [bin2hex($message->bytesEscaped), '005cff'], + 'doubleInfExplicit' => [$message->doubleInfExplicit, null], + 'keywordReserved' => [$message->keywordReserved, Keyword::class_], + ]); + }, + 'defaults overridden' => new Defaults( + doubleInf: -0.5, + doubleNan: 1.0, + floatNan: -\INF, + uint64Max: new Number('18446744073709551614'), + int64Min: PHP_INT_MIN + 1, + bytesOctal: implode('', array_map(chr(...), range(0, 255))), + stringPhp: '{$a}', + ), +]; diff --git a/tests/fixtures/field_defaults/editions.proto b/tests/fixtures/field_defaults/editions.proto new file mode 100644 index 0000000..8e7bc06 --- /dev/null +++ b/tests/fixtures/field_defaults/editions.proto @@ -0,0 +1,18 @@ +edition = "2023"; + +package field.defaults.v1; + +import "field_defaults.proto"; + +// Editions declare defaults the same way, they are baked for LEGACY_REQUIRED fields and enums. +message EditionDefaults { + double double_nan = 1 [features.field_presence = LEGACY_REQUIRED, default = nan]; + float float_neg_inf = 2 [features.field_presence = LEGACY_REQUIRED, default = -inf]; + uint64 uint64_max = 3 [features.field_presence = LEGACY_REQUIRED, default = 18446744073709551615]; + int64 int64_min = 4 [features.field_presence = LEGACY_REQUIRED, default = -9223372036854775808]; + bytes bytes_escaped = 5 [features.field_presence = LEGACY_REQUIRED, default = "\000\\\xff"]; + // Explicit presence: nullable, the declared default is not baked. + double double_inf_explicit = 6 [default = inf]; + // Explicit presence, but an enum with a default is baked. + Keyword keyword_reserved = 7 [default = class]; +} diff --git a/tests/fixtures/field_defaults/field_defaults.proto b/tests/fixtures/field_defaults/field_defaults.proto new file mode 100644 index 0000000..330020d --- /dev/null +++ b/tests/fixtures/field_defaults/field_defaults.proto @@ -0,0 +1,69 @@ +syntax = "proto2"; + +package field.defaults.v1; + +// The default of a field names a value of this enum. +enum Keyword { + option allow_alias = true; + + // A reserved word, the case becomes class_. + class = 0; + // Becomes class_ as well, so it is dropped as the very same member. + class_ = 0; + other = 1; + // Generated as a constant referring to the other case. + other_alias = 1; +} + +// Every field is required, so that its declared default is baked into the constructor. +message Defaults { + // Floating point specials. + required double double_inf = 1 [default = inf]; + required double double_neg_inf = 2 [default = -inf]; + required double double_nan = 3 [default = nan]; + required float float_inf = 4 [default = inf]; + required float float_neg_inf = 5 [default = -inf]; + required float float_nan = 6 [default = nan]; + + // Finite floating point values. + required double double_exponent = 7 [default = 1.5e300]; + required float float_exponent = 8 [default = -1.220703125E-4]; + required double double_integral = 9 [default = 42]; + required double double_max = 10 [default = 1.7976931348623157e308]; + required float float_fraction = 11 [default = 314159.]; + + // Unsigned 64-bit integers, beyond PHP_INT_MAX too. + required uint64 uint64_max = 20 [default = 18446744073709551615]; + required fixed64 fixed64_max = 21 [default = 18446744073709551615]; + required uint64 uint64_above_int = 22 [default = 9223372036854775808]; + required uint64 uint64_int_max = 23 [default = 9223372036854775807]; + required fixed64 fixed64_small = 24 [default = 6400]; + + // Bounds of the signed 64-bit and of the 32-bit integers. + required int64 int64_min = 30 [default = -9223372036854775808]; + required int64 int64_max = 31 [default = 9223372036854775807]; + required sint64 sint64_min = 32 [default = -9223372036854775808]; + required sfixed64 sfixed64_min = 33 [default = -9223372036854775808]; + required sfixed64 sfixed64_max = 34 [default = 9223372036854775807]; + required int32 int32_min = 35 [default = -2147483648]; + required int32 int32_max = 36 [default = 2147483647]; + required sint32 sint32_min = 37 [default = -2147483648]; + required sfixed32 sfixed32_min = 38 [default = -2147483648]; + required uint32 uint32_max = 39 [default = 4294967295]; + required fixed32 fixed32_max = 40 [default = 4294967295]; + + required bool bool_true = 50 [default = true]; + + // Bytes are passed C-escaped by protoc. + required bytes bytes_octal = 60 [default = "\001\002\xff"]; + required bytes bytes_special = 61 [default = "q\"uote'\\back\000nul\x80\xfe\n\r\t$x"]; + + // Strings are passed as is: PHP specials and an escape-like sequence stay literal. + required string string_php = 70 [default = "$var {$x} \\ \"q\" 'a' \n"]; + required string string_escape_like = 71 [default = "a\\001b"]; + required string string_unicode = 72 [default = "привет"]; + + required Keyword keyword_reserved = 80 [default = class]; + required Keyword keyword_dropped = 81 [default = class_]; + required Keyword keyword_alias = 82 [default = other_alias]; +} diff --git a/tests/snapshots/field_defaults/Field/Defaults/V1/Defaults.php b/tests/snapshots/field_defaults/Field/Defaults/V1/Defaults.php new file mode 100644 index 0000000..95fc659 --- /dev/null +++ b/tests/snapshots/field_defaults/Field/Defaults/V1/Defaults.php @@ -0,0 +1,106 @@ +add(Registry\Descriptor::base64(self::EDITIONS_DESCRIPTOR_BUFFER), new File( + name: 'editions.proto', + dependencies: [ + 'field_defaults.proto', + ], + messages: [ + new File\MessageDescriptor('field.defaults.v1.EditionDefaults', \Field\Defaults\V1\EditionDefaults::class), + ], + )); + + $pool->add(Registry\Descriptor::base64(self::FIELD_DEFAULTS_DESCRIPTOR_BUFFER), new File( + name: 'field_defaults.proto', + messages: [ + new File\MessageDescriptor('field.defaults.v1.Defaults', \Field\Defaults\V1\Defaults::class), + ], + enums: [ + new File\EnumDescriptor('field.defaults.v1.Keyword', \Field\Defaults\V1\Keyword::class), + ], + )); + } +} diff --git a/tests/snapshots/field_defaults/Field/Defaults/V1/EditionDefaults.php b/tests/snapshots/field_defaults/Field/Defaults/V1/EditionDefaults.php new file mode 100644 index 0000000..f48d67f --- /dev/null +++ b/tests/snapshots/field_defaults/Field/Defaults/V1/EditionDefaults.php @@ -0,0 +1,44 @@ +register( + new \Thesis\Protobuf\Registry\OnceRegistrar(new \Field\Defaults\V1\DescriptorRegistry()), +);