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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,12 @@ commit into `bench/.cache`.

```sh
bench/run.sh # all three tables: with source info, without it, parsing only
bench/run.sh parity # check that easyprotoc writes the same descriptors as protoc
bench/run.sh parity # compare descriptors against protoc --retain_options
```

The parity check passes `--retain_options` to `protoc` because easyprotoc
includes source-retention options in its descriptor sets.

`MODES` (`full nosrc parse`), `RUNS`, `CORPORA` and `IMPLS` narrow a run, and `CANDIDATE=/path/to/binary`
adds any other protoc-compatible compiler to the table. Results go to
`bench/results/`. See the top of [`bench/run.sh`](bench/run.sh) for the rest.
Expand Down
9 changes: 7 additions & 2 deletions bench/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,14 @@ if [ "$command" = parity ]; then
status=0
for corpus in $corpora; do
for impl in protoc easyprotoc; do
retain_options=""
if [ "$impl" = protoc ]; then
# Match easyprotoc's descriptors, which retain source-only options.
retain_options="--retain_options"
fi
# Both print unused-import warnings on googleapis; show output only on failure.
# shellcheck disable=SC2046
if ! $(impl_cmd "$impl") $(compile_args "$corpus" "$tmp/$impl.pb") >"$tmp/log" 2>&1; then
# shellcheck disable=SC2046,SC2086
if ! $(impl_cmd "$impl") $retain_options $(compile_args "$corpus" "$tmp/$impl.pb") >"$tmp/log" 2>&1; then
cat "$tmp/log" >&2
echo "$corpus: $impl failed" >&2
exit 1
Expand Down
5 changes: 4 additions & 1 deletion internal/compiler/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,10 @@ func (d *Driver) Compile() error {
} else {
fmt.Fprintln(os.Stderr, diag.String())
}
return ErrCompilationFailed
if errors.Is(err, ErrCompilationFailed) {
return err
}
return fmt.Errorf("%w: %w", ErrCompilationFailed, err)
}
}

Expand Down
2 changes: 1 addition & 1 deletion internal/linker/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func (t *SymbolTable) ResolveFile(fileID uint32, f *parser.ASTFile) {
pkg := f.Package.String(f.Src)

// 1. Resolve top-level extensions
for ei := range f.Extensions {
for _, ei := range children(f, f.TopLevelExtensions) {
ext := &f.Extensions[ei]
extFullName := joinScope(pkg, ext.Name.String(f.Src))
if extSymID, ok := t.ByName[extFullName]; ok {
Expand Down
4 changes: 2 additions & 2 deletions internal/linker/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,11 @@ func (t *SymbolTable) indexFileSymbols(fileID uint32, f *parser.ASTFile) {
}

// Top-level Extensions
for ei := range f.Extensions {
for _, ei := range children(f, f.TopLevelExtensions) {
ext := &f.Extensions[ei]
extName := ext.Name.String(f.Src)
extFullName := joinScope(pkg, extName)
symID := t.addSymbol(SymExtension, fileID, NoParent, extName, extFullName, uint32(ei))
symID := t.addSymbol(SymExtension, fileID, NoParent, extName, extFullName, ei)
t.Symbols[symID].TagNumber = ext.Number
t.Symbols[symID].TypeKind = ext.TypeKind
t.Symbols[symID].TypeName = ext.TypeName.String(f.Src)
Expand Down
17 changes: 13 additions & 4 deletions internal/options/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func EvaluateFile(table *linker.SymbolTable, fileID uint32, f *parser.ASTFile) {
f.CustomOptionsWire = evaluateNodeOptions(table, fileID, f, pkg, ".google.protobuf.FileOptions", f.FileOptions)

// 2. Top-level extensions
for ei := range f.Extensions {
for _, ei := range f.ChildIndices[f.TopLevelExtensions.Start:f.TopLevelExtensions.End()] {
ext := &f.Extensions[ei]
ext.CustomOptionsWire = evaluateNodeOptions(table, fileID, f, pkg, ".google.protobuf.FieldOptions", ext.Options)
}
Expand Down Expand Up @@ -135,6 +135,7 @@ func evaluateNodeOptions(table *linker.SymbolTable, fileID uint32, f *parser.AST
// Group root assignments by extension tag
groups := make(map[int32]*tagGroup)
tags := make([]int32, 0, 8)
var rangeOptions []assignment

for i := opts.Start; i < opts.End(); i++ {
optIdx := f.ChildIndices[i]
Expand All @@ -148,7 +149,15 @@ func evaluateNodeOptions(table *linker.SymbolTable, fileID uint32, f *parser.AST
name := firstPart.Name.String(f.Src)
checkStandardOption(f, targetExtendee, opt, name)
if name != "features" {
continue // Standard option, handled in wire serializer
if targetExtendee == extensionRangeOptionsType {
parts := f.OptionNameParts[opt.NameParts.Start:opt.NameParts.End()]
rangeOptions = append(rangeOptions, assignment{nameParts: parts, val: opt})
}
continue
}
if f.Syntax != parser.SyntaxEditions {
optionError(f, optionNamePos(opt), "features can only be specified with editions")
continue
}
tag, ok := featureOptionTags[targetExtendee]
if !ok {
Expand Down Expand Up @@ -219,14 +228,14 @@ func evaluateNodeOptions(table *linker.SymbolTable, fileID uint32, f *parser.AST
grp.assignments = append(grp.assignments, as)
}

out := encodeMessage(table, fileID, f, scope, targetExtendee, rangeOptions)
if len(tags) == 0 {
return nil
return out
}

// Sort tags ascending
sort.Slice(tags, func(i, j int) bool { return tags[i] < tags[j] })

var out []byte
for _, tag := range tags {
grp := groups[tag]
if grp.sym.TypeKind == parser.TypeMessage {
Expand Down
15 changes: 15 additions & 0 deletions internal/options/features.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package options

import (
"strings"

"github.com/easyp-tech/easyprotoc/internal/linker"
"github.com/easyp-tech/easyprotoc/parser"
"google.golang.org/protobuf/reflect/protoreflect"
)

const featureSetTypeName = ".google.protobuf.FeatureSet"
Expand Down Expand Up @@ -152,6 +155,11 @@ func lookupMessageField(table *linker.SymbolTable, msgTypeName, fldName string)
info, found := builtinFeatureSetFields[fldName]
return info, found
}
if msgTypeName == extensionRangeOptionsType || strings.HasPrefix(msgTypeName, extensionRangeOptionsType+".") {
if message, ok := standardDescriptor(msgTypeName).(protoreflect.MessageDescriptor); ok {
return standardField(message, fldName)
}
}
return linker.FieldInfo{}, false
}

Expand All @@ -166,5 +174,12 @@ func lookupEnumValue(table *linker.SymbolTable, typeName, ident string) (int32,
return num, true
}
}
if strings.HasPrefix(typeName, extensionRangeOptionsType+".") {
if enum, ok := standardDescriptor(typeName).(protoreflect.EnumDescriptor); ok {
if value := enum.Values().ByName(protoreflect.Name(ident)); value != nil {
return int32(value.Number()), true
}
}
}
return 0, false
}
41 changes: 41 additions & 0 deletions internal/options/standard.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,46 @@
package options

import (
"strings"

"github.com/easyp-tech/easyprotoc/internal/linker"
"github.com/easyp-tech/easyprotoc/parser"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/descriptorpb"
)

const extensionRangeOptionsType = ".google.protobuf.ExtensionRangeOptions"

func standardDescriptor(name string) protoreflect.Descriptor {
if !strings.HasPrefix(name, ".google.protobuf.") {
return nil
}
descriptor, err := protoregistry.GlobalFiles.FindDescriptorByName(protoreflect.FullName(name[1:]))
if err != nil || descriptor.ParentFile() != descriptorpb.File_google_protobuf_descriptor_proto {
return nil
}
return descriptor
}

func standardField(message protoreflect.MessageDescriptor, name string) (linker.FieldInfo, bool) {
field := message.Fields().ByName(protoreflect.Name(name))
if field == nil {
return linker.FieldInfo{}, false
}
info := linker.FieldInfo{
Name: name, TagNumber: int32(field.Number()),
TypeKind: parser.FieldTypeKind(field.Kind()), Label: parser.FieldLabel(field.Cardinality()),
}
if field.Message() != nil {
info.TypeName = "." + string(field.Message().FullName())
}
if field.Enum() != nil {
info.TypeName = "." + string(field.Enum().FullName())
}
return info, true
}

// standardOptions lists the fields of each google.protobuf.*Options message in
// descriptor.proto (protoc 36.2) and whether each is a bool.
var standardOptions = map[string]map[string]bool{
Expand Down
45 changes: 39 additions & 6 deletions internal/serialize/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,35 @@ func NewWireSerializer() *WireSerializer {
}
}

// A bytes default is C-escaped in FieldDescriptorProto. String defaults
// retain their decoded text.
func fieldDefaultBytes(file *parser.ASTFile, field *parser.FieldNode) []byte {
value := field.DefaultVal.Bytes(file.Src)
if field.TypeKind != parser.TypeBytes {
return value
}
escaped := make([]byte, 0, len(value))
for _, character := range value {
switch character {
case '\n':
escaped = append(escaped, '\\', 'n')
case '\r':
escaped = append(escaped, '\\', 'r')
case '\t':
escaped = append(escaped, '\\', 't')
case '\\', '\'', '"':
escaped = append(escaped, '\\', character)
default:
if character < ' ' || character >= 0x7f {
escaped = append(escaped, '\\', '0'+(character>>6), '0'+((character>>3)&7), '0'+(character&7))
continue
}
escaped = append(escaped, character)
}
}
return escaped
}

func (s *WireSerializer) reset(totalFiles int) {
s.fileSizes = s.fileSizes[:0]
if cap(s.msgSizes) < totalFiles {
Expand Down Expand Up @@ -210,7 +239,7 @@ func (s *WireSerializer) computeFileSize(fileIdx int, f *parser.ASTFile, include
total += tagLen(6) + varintLen(uint64(sSize)) + int(sSize)
}
// Tag 7: extension
for xi := range f.Extensions {
for _, xi := range f.ChildIndices[f.TopLevelExtensions.Start:f.TopLevelExtensions.End()] {
fldSize := s.computeFieldSize(f, &f.Extensions[xi])
total += tagLen(7) + varintLen(uint64(fldSize)) + int(fldSize)
}
Expand Down Expand Up @@ -354,8 +383,9 @@ func (s *WireSerializer) computeFieldSize(f *parser.ASTFile, fld *parser.FieldNo
}

// Tag 7: default_value
if !fld.DefaultVal.IsEmpty() {
total += bytesFieldLen(7, fld.DefaultVal.Bytes(f.Src))
if !fld.DefaultOpt.IsEmpty() || !fld.DefaultVal.IsEmpty() {
value := fieldDefaultBytes(f, fld)
total += tagLen(7) + varintLen(uint64(len(value))) + len(value)
}

// Tag 8: options (FieldOptions)
Expand Down Expand Up @@ -816,7 +846,7 @@ func (s *WireSerializer) writeFileDescriptorProto(buf []byte, pos int, fileIdx i
pos = s.writeServiceDescriptorProto(buf, pos, f, uint32(si))
}
// Tag 7: extension (repeated FieldDescriptorProto)
for xi := range f.Extensions {
for _, xi := range f.ChildIndices[f.TopLevelExtensions.Start:f.TopLevelExtensions.End()] {
fldSize := s.computeFieldSize(f, &f.Extensions[xi])
pos = writeTag(buf, pos, 7, 2)
pos = writeVarint(buf, pos, uint64(fldSize))
Expand Down Expand Up @@ -974,8 +1004,11 @@ func (s *WireSerializer) writeFieldDescriptorProto(buf []byte, pos int, f *parse
}

// Tag 7: default_value
if !fld.DefaultVal.IsEmpty() {
pos = writeBytesField(buf, pos, 7, fld.DefaultVal.Bytes(f.Src))
if !fld.DefaultOpt.IsEmpty() || !fld.DefaultVal.IsEmpty() {
value := fieldDefaultBytes(f, fld)
pos = writeTag(buf, pos, 7, 2)
pos = writeVarint(buf, pos, uint64(len(value)))
pos += copy(buf[pos:], value)
}

// Tag 8: options
Expand Down
15 changes: 12 additions & 3 deletions internal/sourceinfo/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,16 @@ func (g *generator) generateExtensionRangeDecl(erDecl *parser.ExtensionRangeDecl
endSpan = er.StartSpan
}
g.addLoc(append(slicesClone(rPath), 2), endSpan)
if !er.OptionsSpan.IsEmpty() {
optionsPath := append(slicesClone(rPath), 3)
g.addLoc(optionsPath, er.OptionsSpan)
optionCounts := make(map[int32]int32)
var uninterpretedIndex int32
for optionIndex := er.Options.Start; optionIndex < er.Options.End(); optionIndex++ {
option := &g.file.Options[g.file.ChildIndices[optionIndex]]
g.generateOption(option, true, ".google.protobuf.ExtensionRangeOptions", optionsPath, optionCounts, &uninterpretedIndex)
}
}
}
}

Expand Down Expand Up @@ -599,9 +609,8 @@ func (g *generator) generateOption(opt *parser.OptionNode, compact bool, targetT
if !firstPart.IsExtension {
optName := firstPart.Name.String(g.file.Src)
tag = lookupStandardOptionTag(targetType, optName)
if targetType == ".google.protobuf.FieldOptions" && (tag == 19 || tag == 20) {
isRep = true
}
isRep = (targetType == ".google.protobuf.FieldOptions" && (tag == 19 || tag == 20)) ||
(targetType == ".google.protobuf.ExtensionRangeOptions" && optName == "declaration")
} else {
extName := firstPart.Name.String(g.file.Src)
pkg := g.file.Package.String(g.file.Src)
Expand Down
9 changes: 5 additions & 4 deletions parser/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,10 +375,11 @@ type ASTFile struct {
Package TextSpan // Package identifier
PackageSpan TextSpan // Entire package statement span

TopLevelMessages Span32 // Range in ChildIndices pointing to Messages
TopLevelEnums Span32 // Range in ChildIndices pointing to Enums
FileOptions Span32 // Range in ChildIndices pointing to Options
ChildIndices []uint32
TopLevelMessages Span32 // Range in ChildIndices pointing to Messages
TopLevelEnums Span32 // Range in ChildIndices pointing to Enums
TopLevelExtensions Span32 // Range in ChildIndices pointing to file-level Extensions
FileOptions Span32 // Range in ChildIndices pointing to Options
ChildIndices []uint32

Imports []ImportNode
Messages []MessageNode
Expand Down
5 changes: 4 additions & 1 deletion parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ func (p *Parser) ParseFile() (*ASTFile, error) {

topMsgs := make([]uint32, 0, 32)
topEnums := make([]uint32, 0, 16)
var topExtensions []uint32
topOptions := make([]uint32, 0, 16)
seenTypes := make(map[string]bool)

Expand Down Expand Up @@ -361,7 +362,8 @@ func (p *Parser) ParseFile() (*ASTFile, error) {
p.file.Decls = append(p.file.Decls, DeclRef{Kind: DeclService, Index: svcIdx})
case "extend":
p.next()
extBlockIdx, _ := p.parseExtend(nil, tok)
extBlockIdx, extensions := p.parseExtend(nil, tok)
topExtensions = append(topExtensions, extensions...)
p.file.Decls = append(p.file.Decls, DeclRef{Kind: DeclExtend, Index: extBlockIdx})
default:
p.errorAt(tok, fmt.Sprintf("unknown top-level declaration '%s'", ident))
Expand All @@ -371,6 +373,7 @@ func (p *Parser) ParseFile() (*ASTFile, error) {

p.file.TopLevelMessages = p.storeIndices(topMsgs)
p.file.TopLevelEnums = p.storeIndices(topEnums)
p.file.TopLevelExtensions = p.storeIndices(topExtensions)
p.file.FileOptions = p.storeIndices(topOptions)

// Gate post-processing: do not process malformed AST
Expand Down
Loading
Loading