diff --git a/internal/linker/linker_test.go b/internal/linker/linker_test.go index 9c6bcaf..6bc837b 100644 --- a/internal/linker/linker_test.go +++ b/internal/linker/linker_test.go @@ -153,3 +153,62 @@ message Card { t.Errorf("expected .google.actions.sdk.v2.conversation.Image.ImageFill, got %q", fld.TypeName.String(fCard.Src)) } } + +func TestCrossFileFieldEncodingFollowsTheResolvedType(t *testing.T) { + t.Parallel() + fOther := parseTestFile(t, "other.proto", ` +syntax = "proto3"; +package other; + +message Item { int32 a = 1; } +enum Kind { KIND_UNSPECIFIED = 0; } +`) + fMain := parseTestFile(t, "main.proto", ` +syntax = "proto3"; +package main; + +import "other.proto"; + +message Box { + other.Item item = 1; + repeated other.Item items = 2; + other.Kind kind = 3; + repeated other.Kind kinds = 4; + extensions 100 to 199; +} + +extend Box { + repeated other.Item ext_items = 100; + repeated other.Kind ext_kinds = 101; +} +`) + files := []*parser.ASTFile{fOther, fMain} + table := linker.NewSymbolTable(files, map[string]*parser.ASTFile{"other.proto": fOther, "main.proto": fMain}) + table.ResolveTypes() + + fields := table.MessageFields[".main.Box"] + cases := []struct { + name string + implicit, packed bool + }{ + {"item", false, false}, + {"items", false, false}, + {"kind", true, false}, + {"kinds", false, true}, + } + for _, tc := range cases { + info := fields[tc.name] + if info.Implicit != tc.implicit || info.IsPacked != tc.packed { + t.Errorf("field %s: implicit=%v packed=%v, want implicit=%v packed=%v", tc.name, info.Implicit, info.IsPacked, tc.implicit, tc.packed) + } + sym := table.Symbols[table.ByName["main.Box."+tc.name]] + if sym.IsPacked != tc.packed || sym.TypeKind != info.TypeKind { + t.Errorf("field symbol %s: packed=%v kind=%v, want packed=%v kind=%v", tc.name, sym.IsPacked, sym.TypeKind, tc.packed, info.TypeKind) + } + } + for name, packed := range map[string]bool{"main.ext_items": false, "main.ext_kinds": true} { + if sym := table.Symbols[table.ByName[name]]; sym.IsPacked != packed { + t.Errorf("extension %s: packed=%v, want %v", name, sym.IsPacked, packed) + } + } +} diff --git a/internal/linker/presence.go b/internal/linker/presence.go new file mode 100644 index 0000000..b5044d3 --- /dev/null +++ b/internal/linker/presence.go @@ -0,0 +1,92 @@ +package linker + +import "github.com/easyp-tech/easyprotoc/parser" + +// fieldFeatures holds the two features that change how an option value is +// encoded: whether a singular field tracks presence and whether a repeated +// scalar is packed. protoc serializes message-typed option values through a +// DynamicMessage, so a zero in a field without presence is dropped and a +// packed field is written as one length-delimited run. +type fieldFeatures struct { + implicit bool + packed bool +} + +func fileFeatures(f *parser.ASTFile) fieldFeatures { + switch f.Syntax { + case parser.SyntaxProto3: + return fieldFeatures{implicit: true, packed: true} + case parser.SyntaxEditions: + return applyFeatures(f, children(f, f.FileOptions), fieldFeatures{packed: true}) + default: + return fieldFeatures{} + } +} + +// applyFeatures applies `features.field_presence` and +// `features.repeated_field_encoding`, written either as dotted options or as +// a `features = { ... }` literal, on top of the inherited features. +func applyFeatures(f *parser.ASTFile, opts []uint32, base fieldFeatures) fieldFeatures { + if f.Syntax != parser.SyntaxEditions { + return base + } + for _, oi := range opts { + opt := &f.Options[oi] + parts := f.OptionNameParts[opt.NameParts.Start:opt.NameParts.End()] + if len(parts) == 0 || parts[0].IsExtension || parts[0].Name.String(f.Src) != "features" { + continue + } + if len(parts) == 2 && !parts[1].IsExtension { + base = applyFeature(base, parts[1].Name.String(f.Src), opt.ValSpan.String(f.Src)) + continue + } + if len(parts) == 1 && opt.ValKind == parser.OptionValAggregate { + for _, si := range children(f, opt.SubOptions) { + sub := &f.Options[si] + subParts := f.OptionNameParts[sub.NameParts.Start:sub.NameParts.End()] + if len(subParts) == 1 && !subParts[0].IsExtension { + base = applyFeature(base, subParts[0].Name.String(f.Src), sub.ValSpan.String(f.Src)) + } + } + } + } + return base +} + +func applyFeature(base fieldFeatures, name, value string) fieldFeatures { + switch name { + case "field_presence": + base.implicit = value == "IMPLICIT" + case "repeated_field_encoding": + base.packed = value == "PACKED" + } + return base +} + +// fieldEncoding resolves the features of one field declared with the given +// inherited features. +func fieldEncoding(f *parser.ASTFile, fld *parser.FieldNode, inherited fieldFeatures, mapEntry bool) (implicit, packed bool) { + opts := children(f, fld.Options) + resolved := applyFeatures(f, opts, inherited) + message := fld.TypeKind == parser.TypeMessage || fld.TypeKind == parser.TypeGroup + if fld.Label == parser.LabelRepeated { + if message || fld.TypeKind == parser.TypeString || fld.TypeKind == parser.TypeBytes { + return false, false + } + packed = resolved.packed + if f.Syntax != parser.SyntaxEditions { + for _, oi := range opts { + opt := &f.Options[oi] + parts := f.OptionNameParts[opt.NameParts.Start:opt.NameParts.End()] + if len(parts) == 1 && !parts[0].IsExtension && parts[0].Name.String(f.Src) == "packed" { + packed = opt.ValSpan.String(f.Src) == "true" + } + } + } + return false, packed + } + if message || mapEntry || fld.Proto3Optional || fld.OneofIndex >= 0 || !fld.Extendee.IsEmpty() { + return false, false + } + return resolved.implicit, false +} diff --git a/internal/linker/resolve.go b/internal/linker/resolve.go index 6ba229d..04c9802 100644 --- a/internal/linker/resolve.go +++ b/internal/linker/resolve.go @@ -172,6 +172,9 @@ func (t *SymbolTable) resolveExtension(fileID uint32, f *parser.ASTFile, ext *pa ext.TypeName = f.InternString(canonical) t.Symbols[extSymID].TypeKind = ext.TypeKind t.Symbols[extSymID].TypeName = canonical + if ext.TypeKind == parser.TypeMessage { + t.Symbols[extSymID].IsPacked = false + } } } } @@ -198,13 +201,26 @@ func (t *SymbolTable) resolveMessage(fileID uint32, f *parser.ASTFile, msgIdx ui fld.TypeName = f.InternString(canonical) } - // Update FieldInfo + // Update FieldInfo and the field symbol: the encoding was indexed + // before the type resolved, and a message field has neither + // implicit presence nor packing. fldName := fld.Name.String(f.Src) + message := fld.TypeKind == parser.TypeMessage if info, ok := t.MessageFields[canonicalMsg][fldName]; ok { info.TypeKind = fld.TypeKind info.TypeName = fld.TypeName.String(f.Src) + if message { + info.Implicit, info.IsPacked = false, false + } t.MessageFields[canonicalMsg][fldName] = info } + if symID, ok := t.ByName[joinScope(mFullName, fldName)]; ok { + t.Symbols[symID].TypeKind = fld.TypeKind + t.Symbols[symID].TypeName = fld.TypeName.String(f.Src) + if message { + t.Symbols[symID].IsPacked = false + } + } } } diff --git a/internal/linker/symbol.go b/internal/linker/symbol.go index 717f883..0c03b46 100644 --- a/internal/linker/symbol.go +++ b/internal/linker/symbol.go @@ -78,4 +78,5 @@ type FieldInfo struct { TypeName string // Canonical type name with leading dot Label parser.FieldLabel IsPacked bool + Implicit bool // singular field without presence: protoc drops its zero value } diff --git a/internal/linker/table.go b/internal/linker/table.go index c879594..c9a5c48 100644 --- a/internal/linker/table.go +++ b/internal/linker/table.go @@ -235,10 +235,12 @@ func (t *SymbolTable) indexFileSymbols(fileID uint32, f *parser.ASTFile) { t.indexEnum(fileID, f, enumIdx, pkg, NoParent) } + features := fileFeatures(f) + // Top-level Messages for i := f.TopLevelMessages.Start; i < f.TopLevelMessages.End(); i++ { msgIdx := f.ChildIndices[i] - t.indexMessage(fileID, f, msgIdx, pkg, NoParent) + t.indexMessage(fileID, f, msgIdx, pkg, NoParent, features) } // Top-level Extensions @@ -247,6 +249,7 @@ func (t *SymbolTable) indexFileSymbols(fileID uint32, f *parser.ASTFile) { extName := ext.Name.String(f.Src) extFullName := joinScope(pkg, extName) symID := t.addSymbol(SymExtension, fileID, NoParent, extName, extFullName, ei) + _, t.Symbols[symID].IsPacked = fieldEncoding(f, ext, features, false) t.Symbols[symID].TagNumber = ext.Number t.Symbols[symID].TypeKind = ext.TypeKind t.Symbols[symID].TypeName = ext.TypeName.String(f.Src) @@ -302,8 +305,9 @@ func (t *SymbolTable) indexEnum(fileID uint32, f *parser.ASTFile, enumIdx uint32 } } -func (t *SymbolTable) indexMessage(fileID uint32, f *parser.ASTFile, msgIdx uint32, parentScope string, parentSymID uint32) { +func (t *SymbolTable) indexMessage(fileID uint32, f *parser.ASTFile, msgIdx uint32, parentScope string, parentSymID uint32, inherited fieldFeatures) { m := &f.Messages[msgIdx] + features := applyFeatures(f, children(f, m.Options), inherited) mName := m.Name.String(f.Src) mFullName := joinScope(parentScope, mName) canonicalMsg := "." + mFullName @@ -324,6 +328,8 @@ func (t *SymbolTable) indexMessage(fileID uint32, f *parser.ASTFile, msgIdx uint t.Symbols[fldSymID].TypeKind = fld.TypeKind t.Symbols[fldSymID].TypeName = fld.TypeName.String(f.Src) t.Symbols[fldSymID].Label = fld.Label + implicit, packed := fieldEncoding(f, fld, features, m.IsMapEntry) + t.Symbols[fldSymID].IsPacked = packed t.MessageFields[canonicalMsg][fldName] = FieldInfo{ Name: fldName, @@ -331,6 +337,8 @@ func (t *SymbolTable) indexMessage(fileID uint32, f *parser.ASTFile, msgIdx uint TypeKind: fld.TypeKind, TypeName: fld.TypeName.String(f.Src), Label: fld.Label, + IsPacked: packed, + Implicit: implicit, } } @@ -343,7 +351,7 @@ func (t *SymbolTable) indexMessage(fileID uint32, f *parser.ASTFile, msgIdx uint // Index nested messages for nmi := m.NestedMessages.Start; nmi < m.NestedMessages.End(); nmi++ { subMsgIdx := f.ChildIndices[nmi] - t.indexMessage(fileID, f, subMsgIdx, mFullName, msgSymID) + t.indexMessage(fileID, f, subMsgIdx, mFullName, msgSymID, features) } // Index nested extensions @@ -353,6 +361,7 @@ func (t *SymbolTable) indexMessage(fileID uint32, f *parser.ASTFile, msgIdx uint extName := ext.Name.String(f.Src) extFullName := joinScope(mFullName, extName) extSymID := t.addSymbol(SymExtension, fileID, msgSymID, extName, extFullName, extIdx) + _, t.Symbols[extSymID].IsPacked = fieldEncoding(f, ext, features, false) t.Symbols[extSymID].TagNumber = ext.Number t.Symbols[extSymID].TypeKind = ext.TypeKind t.Symbols[extSymID].TypeName = ext.TypeName.String(f.Src) diff --git a/internal/options/evaluator.go b/internal/options/evaluator.go index b844086..76df92e 100644 --- a/internal/options/evaluator.go +++ b/internal/options/evaluator.go @@ -292,17 +292,8 @@ func evaluateNodeOptions(table *linker.SymbolTable, fileID uint32, f *parser.AST out = append(out, msgBytes...) } } else { - // Scalar / Enum extension - for _, as := range grp.assignments { - if as.val.ValKind == parser.OptionValList { - for ei := as.val.SubOptions.Start; ei < as.val.SubOptions.End(); ei++ { - elem := &f.Options[f.ChildIndices[ei]] - encodeScalarOrEnum(&out, tag, grp.sym.TypeKind, grp.sym.TypeName, table, fileID, f, scope, elem) - } - } else { - encodeScalarOrEnum(&out, tag, grp.sym.TypeKind, grp.sym.TypeName, table, fileID, f, scope, as.val) - } - } + info := linker.FieldInfo{TagNumber: tag, TypeKind: grp.sym.TypeKind, TypeName: grp.sym.TypeName, IsPacked: grp.sym.IsPacked} + out = encodeScalarField(out, info, grp.assignments, table, fileID, f, scope) } } @@ -350,6 +341,7 @@ func encodeMessage(table *linker.SymbolTable, fileID uint32, f *parser.ASTFile, TypeKind: extSym.TypeKind, TypeName: extSym.TypeName, Label: extSym.Label, + IsPacked: extSym.IsPacked, } found = true } else if msgTypeName == featureSetTypeName { @@ -429,23 +421,62 @@ func encodeMessage(table *linker.SymbolTable, fileID uint32, f *parser.ASTFile, msgBuf = append(msgBuf, subBytes...) } } else { - // Scalar / Enum field - for _, as := range grp.assignments { - if as.val.ValKind == parser.OptionValList { - for ei := as.val.SubOptions.Start; ei < as.val.SubOptions.End(); ei++ { - elem := &f.Options[f.ChildIndices[ei]] - encodeScalarOrEnum(&msgBuf, tag, grp.info.TypeKind, grp.info.TypeName, table, fileID, f, scope, elem) - } - } else { - encodeScalarOrEnum(&msgBuf, tag, grp.info.TypeKind, grp.info.TypeName, table, fileID, f, scope, as.val) - } - } + msgBuf = encodeScalarField(msgBuf, grp.info, grp.assignments, table, fileID, f, scope) } } return msgBuf } +// encodeScalarField writes the values of one scalar or enum field of an +// option message the way protoc serializes the parsed message: a packed field +// as one length-delimited run, and no zero value for a field without presence. +func encodeScalarField(buf []byte, info linker.FieldInfo, assignments []assignment, table *linker.SymbolTable, fileID uint32, f *parser.ASTFile, scope string) []byte { + var values []*parser.OptionNode + for _, as := range assignments { + if as.val.ValKind != parser.OptionValList { + values = append(values, as.val) + continue + } + for ei := as.val.SubOptions.Start; ei < as.val.SubOptions.End(); ei++ { + values = append(values, &f.Options[f.ChildIndices[ei]]) + } + } + tagSize := len(appendTag(nil, uint32(info.TagNumber), 0)) + var packed []byte + for _, v := range values { + var field []byte + encodeScalarOrEnum(&field, info.TagNumber, info.TypeKind, info.TypeName, table, fileID, f, scope, v) + if len(field) == 0 { + continue + } + value := field[tagSize:] + switch { + case info.IsPacked: + packed = append(packed, value...) + case info.Implicit && isZero(value): + default: + buf = append(buf, field...) + } + } + if len(packed) > 0 { + buf = appendBytesField(buf, uint32(info.TagNumber), packed) + } + return buf +} + +// isZero reports whether an encoded value, without its tag, is the zero of +// its type: a zero varint, all-zero fixed bits or an empty length-delimited +// value. Negative zero keeps its sign bit and is not zero, as in protoc. +func isZero(value []byte) bool { + for _, b := range value { + if b != 0 { + return false + } + } + return true +} + func encodeScalarOrEnum(buf *[]byte, tag int32, typeKind parser.FieldTypeKind, typeName string, table *linker.SymbolTable, fileID uint32, f *parser.ASTFile, scope string, opt *parser.OptionNode) { switch typeKind { case parser.TypeBool: diff --git a/protoc/option_encoding_test.go b/protoc/option_encoding_test.go new file mode 100644 index 0000000..8ab51a7 --- /dev/null +++ b/protoc/option_encoding_test.go @@ -0,0 +1,136 @@ +package protoc + +import ( + "encoding/hex" + "slices" + "testing" + + "google.golang.org/protobuf/proto" +) + +// The wanted bytes are what protoc 36.2 writes for the same sources. +func TestOptionValuesEncodeLikeProtoc(t *testing.T) { + t.Parallel() + cases := []struct { + name string + source string + want []string + }{ + { + name: "proto3 drops zeros without presence and packs scalars", + source: `syntax = "proto3"; +package p3; +import "google/protobuf/descriptor.proto"; +enum Color { COLOR_UNSPECIFIED = 0; COLOR_RED = 1; } +message Flag { + bool on = 1; + string name = 2; + int32 n = 3; + Color color = 4; + optional int32 opt = 5; + oneof kind { int32 k = 6; string s = 7; } + repeated int32 nums = 8; + bytes raw = 9; + double d = 10; +} +extend google.protobuf.EnumValueOptions { Flag flag = 50000; } +enum Feature { + FEATURE_UNSPECIFIED = 0; + FEATURE_A = 1 [(flag) = {on: false, name: "", n: 0, color: COLOR_UNSPECIFIED, opt: 0, k: 0, nums: [1, 2, 0], raw: "", d: 0}]; + FEATURE_B = 2 [(flag).on = false, (flag).name = "b"]; +}`, + want: []string{"82b51809280030004203010200", "82b51803120162"}, + }, + { + name: "proto2 keeps zeros and packs only packed fields", + source: `syntax = "proto2"; +package p2; +import "google/protobuf/descriptor.proto"; +message Flag { optional bool on = 1; optional string name = 2; repeated int32 nums = 3; repeated int32 packed = 4 [packed = true]; } +extend google.protobuf.EnumValueOptions { optional Flag flag = 50001; } +enum Feature { FEATURE_UNSPECIFIED = 0; FEATURE_A = 1 [(flag) = {on: false, name: "", nums: [1, 0], packed: [1, 0]}]; }`, + want: []string{"8ab5180c080012001801180022020100"}, + }, + { + name: "editions follow field_presence and repeated_field_encoding", + source: `edition = "2023"; +package ed; +import "google/protobuf/descriptor.proto"; +message Flag { bool on = 1; bool imp = 2 [features.field_presence = IMPLICIT]; repeated int32 nums = 3; repeated int32 exp = 4 [features.repeated_field_encoding = EXPANDED]; } +extend google.protobuf.EnumValueOptions { Flag flag = 50002; } +enum Feature { FEATURE_UNSPECIFIED = 0; FEATURE_A = 1 [(flag) = {on: false, imp: false, nums: [1, 0], exp: [1, 0]}]; }`, + want: []string{"92b5180a08001a02010020012000"}, + }, + { + name: "repeated extensions pack and nested messages keep their rules", + source: `syntax = "proto3"; +package top; +import "google/protobuf/descriptor.proto"; +message Inner { int32 a = 1; repeated int32 xs = 2; map m = 3; } +message Outer { Inner in = 1; repeated Inner ins = 2; bool b = 3; } +extend google.protobuf.EnumValueOptions { + repeated int32 ints = 50010; + int32 one = 50011; + Outer outer = 50012; +} +enum Feature { + FEATURE_UNSPECIFIED = 0; + FEATURE_A = 1 [(ints) = 1, (ints) = 0, (one) = 0, (outer) = {in: {a: 0, xs: [0, 3]}, ins: [{a: 0}, {a: 2, m: [{key: "", value: 0}]}], b: false}]; +}`, + want: []string{"d2b518020100d8b51800e2b518120a04120200031200120808021a040a001000"}, + }, + { + name: "proto2 extensions inside an option message pack when packed", + source: `syntax = "proto2"; +package n1; +import "google/protobuf/descriptor.proto"; +message Box { extensions 100 to 199; } +extend Box { repeated int32 ext_packed = 101 [packed = true]; repeated int32 ext_plain = 102; } +extend google.protobuf.EnumValueOptions { optional Box box = 50020; } +enum Feature { + FEATURE_UNSPECIFIED = 0; + FEATURE_A = 1 [(box) = { [n1.ext_packed]: [1, 2, 0], [n1.ext_plain]: [1, 0] }]; + FEATURE_B = 2 [(box).(n1.ext_packed) = 1, (box).(n1.ext_packed) = 0]; +}`, + want: []string{"a2b6180caa0603010200b00601b00600", "a2b61805aa06020100"}, + }, + { + name: "editions extensions inside an option message follow repeated_field_encoding", + source: `edition = "2023"; +package n2; +import "google/protobuf/descriptor.proto"; +message Box { extensions 100 to 199; } +extend Box { repeated int32 ext_packed = 101; repeated int32 ext_expanded = 102 [features.repeated_field_encoding = EXPANDED]; } +extend google.protobuf.EnumValueOptions { Box box = 50021; } +enum Feature { + FEATURE_UNSPECIFIED = 0; + FEATURE_A = 1 [(box) = { [n2.ext_packed]: [1, 2, 0], [n2.ext_expanded]: [1, 0] }]; +}`, + want: []string{"aab6180caa0603010200b00601b00600"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + result, err := Compile(t.Context(), []string{"options.proto"}, WithResolverOnly(MemResolver{"options.proto": []byte(tc.source)}), WithStandardImports(true)) + if err != nil { + t.Fatal(err) + } + file := result.DescriptorSet().File[0] + var got []string + for _, value := range file.EnumType[len(file.EnumType)-1].Value { + if value.Options == nil { + continue + } + raw, err := proto.Marshal(value.Options) + if err != nil { + t.Fatal(err) + } + got = append(got, hex.EncodeToString(raw)) + } + if !slices.Equal(got, tc.want) { + t.Errorf("options = %v, want %v", got, tc.want) + } + }) + } +}