diff --git a/README.md b/README.md index c68ad39..aed8c28 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/bench/run.sh b/bench/run.sh index e8afcd8..1a190be 100755 --- a/bench/run.sh +++ b/bench/run.sh @@ -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 diff --git a/internal/compiler/driver.go b/internal/compiler/driver.go index 17bee0b..76f5285 100644 --- a/internal/compiler/driver.go +++ b/internal/compiler/driver.go @@ -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) } } diff --git a/internal/linker/resolve.go b/internal/linker/resolve.go index 34eee12..6ba229d 100644 --- a/internal/linker/resolve.go +++ b/internal/linker/resolve.go @@ -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 { diff --git a/internal/linker/table.go b/internal/linker/table.go index 33674dd..c879594 100644 --- a/internal/linker/table.go +++ b/internal/linker/table.go @@ -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) diff --git a/internal/options/evaluator.go b/internal/options/evaluator.go index d911528..b844086 100644 --- a/internal/options/evaluator.go +++ b/internal/options/evaluator.go @@ -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) } @@ -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] @@ -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 { @@ -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 { diff --git a/internal/options/features.go b/internal/options/features.go index 0913012..a712daa 100644 --- a/internal/options/features.go +++ b/internal/options/features.go @@ -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" @@ -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 } @@ -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 } diff --git a/internal/options/standard.go b/internal/options/standard.go index c749c47..41687b5 100644 --- a/internal/options/standard.go +++ b/internal/options/standard.go @@ -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{ diff --git a/internal/serialize/wire.go b/internal/serialize/wire.go index dc0a32c..1885e9f 100644 --- a/internal/serialize/wire.go +++ b/internal/serialize/wire.go @@ -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 { @@ -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) } @@ -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) @@ -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)) @@ -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 diff --git a/internal/sourceinfo/generator.go b/internal/sourceinfo/generator.go index a8dc20c..1f7cba9 100644 --- a/internal/sourceinfo/generator.go +++ b/internal/sourceinfo/generator.go @@ -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) + } + } } } @@ -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) diff --git a/parser/ast.go b/parser/ast.go index 48ac540..077fff1 100644 --- a/parser/ast.go +++ b/parser/ast.go @@ -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 diff --git a/parser/parser.go b/parser/parser.go index 2ada78d..ae44093 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -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) @@ -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)) @@ -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 diff --git a/protoc/compile.go b/protoc/compile.go index c0f46ef..f7f27c4 100644 --- a/protoc/compile.go +++ b/protoc/compile.go @@ -49,7 +49,7 @@ func Compile(ctx context.Context, files []string, opts ...Option) (*Result, erro var outBytes []byte var orderedFiles []*parser.ASTFile - useCustomResolvers := len(cfg.resolvers) > 0 || cfg.standardImports + useCustomResolvers := cfg.resolverOnly || len(cfg.resolvers) > 0 || cfg.standardImports var readFileCb func(string) ([]byte, error) var resolvePathCb func(string) (string, string, error) if useCustomResolvers { @@ -79,9 +79,6 @@ func Compile(ctx context.Context, files []string, opts ...Option) (*Result, erro driver := compiler.NewDriver(driverOpts) if err := driver.Compile(); err != nil { - if errors.Is(err, compiler.ErrCompilationFailed) { - return nil, ErrCompilationFailed - } return nil, err } @@ -101,7 +98,7 @@ func Compile(ctx context.Context, files []string, opts ...Option) (*Result, erro filesToGen = append(filesToGen, c) continue } - cleanF := strings.TrimPrefix(filepath.Clean(filepath.ToSlash(f)), "./") + cleanF := filepath.ToSlash(filepath.Clean(f)) if c, ok := knownCanon[cleanF]; ok { filesToGen = append(filesToGen, c) continue @@ -153,8 +150,11 @@ func (cfg *compileConfig) sources(ctx context.Context, withDirs bool) ([]string, var resolvers []Resolver resolvers = append(resolvers, cfg.resolvers...) - allowDisk := withDirs && len(cfg.resolvers) == 0 + allowDisk := withDirs && !cfg.resolverOnly && len(cfg.resolvers) == 0 importPaths := cfg.importPaths + if cfg.resolverOnly { + importPaths = nil + } if allowDisk && len(importPaths) == 0 { importPaths = []string{"."} } @@ -190,8 +190,7 @@ func (cfg *compileConfig) sources(ctx context.Context, withDirs bool) ([]string, return "", "", ctx.Err() } - cleanPath := filepath.Clean(filepath.ToSlash(path)) - cleanPath = strings.TrimPrefix(cleanPath, "./") + cleanPath := filepath.ToSlash(filepath.Clean(path)) // 1. Check if relative to each import path in order for _, ip := range importPaths { diff --git a/protoc/generation_metadata_test.go b/protoc/generation_metadata_test.go new file mode 100644 index 0000000..9369907 --- /dev/null +++ b/protoc/generation_metadata_test.go @@ -0,0 +1,130 @@ +package protoc + +import ( + "bytes" + "slices" + "testing" + + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/types/descriptorpb" +) + +func TestCompileKeepsExtensionRangeOptions(t *testing.T) { + t.Parallel() + result, err := Compile(t.Context(), []string{"range.proto"}, WithResolverOnly(MemResolver{ + "range.proto": []byte(`syntax = "proto2"; +package sample; +message Message { + extensions 100 to 199 [ + declaration = { number: 100, full_name: ".sample.ext", type: "string" }, + declaration = { number: 104, reserved: true }, + verification = DECLARATION + ]; +}`), + }), WithIncludeSourceInfo(true)) + if err != nil { + t.Fatal(err) + } + opts := result.DescriptorSet().File[0].MessageType[0].ExtensionRange[0].GetOptions() + declarations := opts.GetDeclaration() + if len(declarations) != 2 || + declarations[0].GetNumber() != 100 || declarations[0].GetFullName() != ".sample.ext" || declarations[0].GetType() != "string" || + declarations[1].GetNumber() != 104 || !declarations[1].GetReserved() { + t.Fatalf("declarations = %v", declarations) + } + if opts.Verification == nil || opts.GetVerification() != descriptorpb.ExtensionRangeOptions_DECLARATION { + t.Fatalf("verification = %v", opts) + } + + optionPath := []int32{4, 0, 5, 0, 3} + want := []struct { + path []int32 + span []int32 + }{ + {optionPath, []int32{3, 24, 7, 3}}, + {[]int32{4, 0, 5, 0, 3, 2, 0}, []int32{4, 4, 75}}, + {[]int32{4, 0, 5, 0, 3, 2, 1}, []int32{5, 4, 49}}, + {[]int32{4, 0, 5, 0, 3, 3}, []int32{6, 4, 30}}, + } + var locations []*descriptorpb.SourceCodeInfo_Location + for _, location := range result.DescriptorSet().File[0].GetSourceCodeInfo().GetLocation() { + path := location.GetPath() + if len(path) >= len(optionPath) && slices.Equal(path[:len(optionPath)], optionPath) { + locations = append(locations, location) + } + } + if len(locations) != len(want) { + t.Fatalf("extension range option locations = %v, want %d locations", locations, len(want)) + } + for index, location := range locations { + if !slices.Equal(location.GetPath(), want[index].path) || !slices.Equal(location.GetSpan(), want[index].span) { + t.Errorf("location %d = %v, want path %v and span %v", index, location, want[index].path, want[index].span) + } + } +} + +func TestCompileKeepsEditionFeatures(t *testing.T) { + t.Parallel() + result, err := Compile(t.Context(), []string{"edition.proto"}, WithResolverOnly(MemResolver{ + "edition.proto": []byte(`edition = "2023"; +option features.field_presence = IMPLICIT; +message Record { int32 value = 1 [features.field_presence = EXPLICIT]; }`), + })) + if err != nil { + t.Fatal(err) + } + file := result.DescriptorSet().File[0] + if got := file.GetOptions().GetFeatures().GetFieldPresence(); got != descriptorpb.FeatureSet_IMPLICIT { + t.Fatalf("file field_presence = %v, want IMPLICIT", got) + } + if got := file.MessageType[0].Field[0].GetOptions().GetFeatures().GetFieldPresence(); got != descriptorpb.FeatureSet_EXPLICIT { + t.Fatalf("field field_presence = %v, want EXPLICIT", got) + } +} + +func TestCompileKeepsExplicitDefaults(t *testing.T) { + t.Parallel() + result, err := Compile(t.Context(), []string{"defaults.proto"}, WithResolverOnly(MemResolver{ + "defaults.proto": []byte(`syntax = "proto2"; +message Record { + optional string text = 1 [default = ""]; + optional bytes data = 2 [default = "\000\377\n\\"]; +}`), + })) + if err != nil { + t.Fatal(err) + } + file, err := protodesc.NewFile(result.DescriptorSet().File[0], nil) + if err != nil { + t.Fatal(err) + } + fields := file.Messages().Get(0).Fields() + if field := fields.ByName("text"); !field.HasDefault() || field.Default().String() != "" { + t.Fatalf("text.HasDefault() = %v, default = %q", field.HasDefault(), field.Default()) + } + if data := fields.ByName("data").Default().Bytes(); !bytes.Equal(data, []byte{0, 255, '\n', '\\'}) { + t.Fatalf("data default = %q", data) + } +} + +func TestCompileKeepsNestedExtensionScope(t *testing.T) { + t.Parallel() + result, err := Compile(t.Context(), []string{"nested.proto"}, WithResolverOnly(MemResolver{ + "nested.proto": []byte(`syntax = "proto2"; +package sample; +message Target { extensions 100 to 199; } +message Holder { + message Value {} + extend Target { optional Value nested = 100; } +}`), + })) + if err != nil { + t.Fatal(err) + } + file := result.DescriptorSet().File[0] + extensions := file.MessageType[1].GetExtension() + if len(file.GetExtension()) != 0 || len(extensions) != 1 || + extensions[0].GetTypeName() != ".sample.Holder.Value" || extensions[0].GetExtendee() != ".sample.Target" { + t.Fatalf("file extensions = %v, Holder extensions = %v", file.GetExtension(), extensions) + } +} diff --git a/protoc/link.go b/protoc/link.go index 1194065..82b2e88 100644 --- a/protoc/link.go +++ b/protoc/link.go @@ -97,9 +97,6 @@ func Link(ctx context.Context, files []string, opts ...Option) (*Linked, error) }, }) if err := driver.Compile(); err != nil { - if errors.Is(err, compiler.ErrCompilationFailed) { - return nil, ErrCompilationFailed - } return nil, err } diff --git a/protoc/options.go b/protoc/options.go index 38faf37..7acdae3 100644 --- a/protoc/options.go +++ b/protoc/options.go @@ -5,6 +5,7 @@ type Option func(*compileConfig) type compileConfig struct { resolvers []Resolver + resolverOnly bool importPaths []string includeImports bool includeSourceInfo bool @@ -33,6 +34,16 @@ func WithResolver(r Resolver) Option { } } +// WithResolverOnly adds a resolver and disables file system fallbacks. Names +// passed to resolvers are normalized logical paths. WithResolver and +// WithStandardImports can explicitly add further sources. +func WithResolverOnly(r Resolver) Option { + return func(c *compileConfig) { + c.resolverOnly = true + WithResolver(r)(c) + } +} + // WithImportPaths adds directory search paths for imports. func WithImportPaths(paths ...string) Option { return func(c *compileConfig) { diff --git a/protoc/resolver.go b/protoc/resolver.go index 8112e9e..e91442c 100644 --- a/protoc/resolver.go +++ b/protoc/resolver.go @@ -21,6 +21,14 @@ type Resolver interface { FindFileByPath(ctx context.Context, path string) ([]byte, error) } +// ResolverFunc adapts a source lookup function to Resolver. +type ResolverFunc func(context.Context, string) ([]byte, error) + +// FindFileByPath implements Resolver. +func (f ResolverFunc) FindFileByPath(ctx context.Context, path string) ([]byte, error) { + return f(ctx, path) +} + // MemResolver resolves proto files directly from an in-memory map. type MemResolver map[string][]byte diff --git a/protoc/resolver_only_test.go b/protoc/resolver_only_test.go new file mode 100644 index 0000000..d6b5897 --- /dev/null +++ b/protoc/resolver_only_test.go @@ -0,0 +1,39 @@ +package protoc + +import ( + "context" + "errors" + "io/fs" + "os" + "testing" +) + +func TestCompileResolverOnlyDoesNotReadDisk(t *testing.T) { + dir := t.TempDir() + t.Chdir(dir) + if err := os.WriteFile("blocked.proto", []byte(`syntax = "proto3"; message Blocked {}`), 0o644); err != nil { + t.Fatal(err) + } + for _, cause := range []error{ErrFileNotFound, fs.ErrPermission} { + t.Run(cause.Error(), func(t *testing.T) { + resolve := ResolverFunc(func(_ context.Context, path string) ([]byte, error) { + if path == "entry.proto" { + return []byte(`syntax = "proto3"; import "blocked.proto"; message Entry { Blocked value = 1; }`), nil + } + return nil, cause + }) + var diagnostics []Diagnostic + result, err := Compile(t.Context(), []string{"./entry.proto"}, + WithImportPaths(dir), WithResolverOnly(resolve), WithErrorHandler(func(d Diagnostic) { + diagnostics = append(diagnostics, d) + }), + ) + if result != nil || !errors.Is(err, cause) { + t.Fatalf("Compile = %v, %v, want failure wrapping %v", result, err, cause) + } + if errors.Is(cause, ErrFileNotFound) && (len(diagnostics) != 1 || diagnostics[0].Path != "entry.proto") { + t.Fatalf("diagnostics = %v, want an import diagnostic at entry.proto", diagnostics) + } + }) + } +}