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
59 changes: 59 additions & 0 deletions internal/linker/linker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
92 changes: 92 additions & 0 deletions internal/linker/presence.go
Original file line number Diff line number Diff line change
@@ -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
}
18 changes: 17 additions & 1 deletion internal/linker/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
}
Expand All @@ -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
}
}
}
}

Expand Down
1 change: 1 addition & 0 deletions internal/linker/symbol.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
15 changes: 12 additions & 3 deletions internal/linker/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -324,13 +328,17 @@ 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,
TagNumber: fld.Number,
TypeKind: fld.TypeKind,
TypeName: fld.TypeName.String(f.Src),
Label: fld.Label,
IsPacked: packed,
Implicit: implicit,
}
}

Expand All @@ -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
Expand All @@ -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)
Expand Down
75 changes: 53 additions & 22 deletions internal/options/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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:
Expand Down
Loading