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
29 changes: 16 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> 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<string, string> x = 1;` | `\Thesis\Protobuf\Map $x = new \Thesis\Protobuf\Map()` |

**proto3**

Expand Down
187 changes: 163 additions & 24 deletions src/Plugin/Generator/ProtoGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
131 changes: 131 additions & 0 deletions tests/CompilerDefaultValueTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?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\Compiler\CodeGeneratorResponse;
use Thesis\Google\Protobuf\DescriptorProto;
use Thesis\Google\Protobuf\EnumDescriptorProto;
use Thesis\Google\Protobuf\EnumValueDescriptorProto;
use Thesis\Google\Protobuf\FieldDescriptorProto;
use Thesis\Google\Protobuf\FieldDescriptorProto\Type;
use Thesis\Google\Protobuf\FileDescriptorProto;
use Thesis\Protobuf\Encoder;
use Thesis\Protoc\Exception\CodeCannotBeGenerated;
use Thesis\Protoc\Plugin\Compiler;
use Thesis\Protoc\Plugin\Generator\ProtoGenerator;

/**
* A declared default that cannot be read for the type of its field is reported, instead of silently becoming
* 0 or false. protoc validates defaults itself, so such descriptors can only come from another source.
* The valid defaults are covered by the field_defaults snapshot case.
*/
#[CoversClass(Compiler::class)]
#[CoversClass(ProtoGenerator::class)]
final class CompilerDefaultValueTest extends TestCase
{
#[DataProvider('provideInvalidDefaultIsReportedCases')]
public function testInvalidDefaultIsReported(Type $type, string $default, string $error): void
{
$this->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<string, array{Type, string, string}>
*/
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<CodeGeneratorResponse\File>
* @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);
}
}
3 changes: 2 additions & 1 deletion tests/GeneratedCode/GeneratedCodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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/<case>.php.
* populated samples from samples/<case>.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.
Expand Down
Loading