From 5b457c6f7bbe261af01d63f212762973cbccf7cd Mon Sep 17 00:00:00 2001 From: shota3506 Date: Mon, 13 Oct 2025 21:27:11 +0900 Subject: [PATCH] replace github.com/jhump/protoreflect/desc/protoparse with github.com/bufbuild/protocompile --- go.mod | 2 +- internal/js/modules/k6/grpc/client.go | 35 +- internal/lib/netext/grpcext/conn_test.go | 23 +- .../jhump/protoreflect/desc/protoparse/ast.go | 716 ---------------- .../protoreflect/desc/protoparse/ast/doc.go | 27 - .../protoreflect/desc/protoparse/ast/enum.go | 154 ---- .../protoreflect/desc/protoparse/ast/field.go | 659 -------------- .../protoreflect/desc/protoparse/ast/file.go | 236 ----- .../desc/protoparse/ast/identifiers.go | 134 --- .../desc/protoparse/ast/message.go | 199 ----- .../desc/protoparse/ast/no_source.go | 103 --- .../protoreflect/desc/protoparse/ast/node.go | 200 ----- .../desc/protoparse/ast/options.go | 361 -------- .../protoreflect/desc/protoparse/ast/print.go | 86 -- .../desc/protoparse/ast/ranges.go | 305 ------- .../desc/protoparse/ast/service.go | 273 ------ .../desc/protoparse/ast/source_pos.go | 29 - .../desc/protoparse/ast/values.go | 575 ------------- .../protoreflect/desc/protoparse/ast/walk.go | 497 ----------- .../jhump/protoreflect/desc/protoparse/doc.go | 16 - .../protoreflect/desc/protoparse/errors.go | 122 --- .../protoreflect/desc/protoparse/parser.go | 804 ------------------ .../desc/protoparse/resolve_files.go | 175 ---- vendor/modules.txt | 2 - 24 files changed, 34 insertions(+), 5699 deletions(-) delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/doc.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/enum.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/field.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/file.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/identifiers.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/message.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/no_source.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/node.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/options.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/print.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/ranges.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/service.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/source_pos.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/values.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/ast/walk.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/doc.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/errors.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/parser.go delete mode 100644 vendor/github.com/jhump/protoreflect/desc/protoparse/resolve_files.go diff --git a/go.mod b/go.mod index cd0f9725b..3cbd8d9c2 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/PuerkitoBio/goquery v1.10.3 github.com/Soontao/goHttpDigestClient v0.0.0-20170320082612-6d28bb1415c5 github.com/andybalholm/brotli v1.2.0 + github.com/bufbuild/protocompile v0.14.1 github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d github.com/evanw/esbuild v0.25.10 github.com/fatih/color v1.18.0 @@ -70,7 +71,6 @@ require ( buf.build/gen/go/gogo/protobuf/protocolbuffers/go v1.36.10-20240617172848-e1dbca2775a7.1 // indirect github.com/andybalholm/cascadia v1.3.3 // indirect github.com/beorn7/perks v1.0.1 // indirect - github.com/bufbuild/protocompile v0.14.1 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chromedp/sysutil v1.1.0 // indirect diff --git a/internal/js/modules/k6/grpc/client.go b/internal/js/modules/k6/grpc/client.go index 0396c4962..04ce97c0f 100644 --- a/internal/js/modules/k6/grpc/client.go +++ b/internal/js/modules/k6/grpc/client.go @@ -18,9 +18,8 @@ import ( "go.k6.io/k6/js/common" "go.k6.io/k6/js/modules" + "github.com/bufbuild/protocompile" "github.com/grafana/sobek" - "github.com/jhump/protoreflect/desc" //nolint:staticcheck // FIXME: #4035 - "github.com/jhump/protoreflect/desc/protoparse" //nolint:staticcheck // FIXME: #4035 "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" @@ -65,22 +64,24 @@ func (c *Client) Load(importPaths []string, filenames ...string) ([]MethodInfo, importPaths[i] = strings.TrimPrefix(s, "file://") } - parser := protoparse.Parser{ - ImportPaths: importPaths, - InferImportPaths: false, - Accessor: protoparse.FileAccessor(func(filename string) (io.ReadCloser, error) { + resolver := protocompile.WithStandardImports(&protocompile.SourceResolver{ + ImportPaths: importPaths, + Accessor: func(filename string) (io.ReadCloser, error) { absFilePath := initEnv.GetAbsFilePath(filename) return initEnv.FileSystems["file"].Open(absFilePath) - }), + }, + }) + + compiler := protocompile.Compiler{ + Resolver: resolver, } - fds, err := parser.ParseFiles(filenames...) + fds, err := compiler.Compile(c.vu.Context(), filenames...) if err != nil { return nil, err } fdset := &descriptorpb.FileDescriptorSet{} - seen := make(map[string]struct{}) for _, fd := range fds { fdset.File = append(fdset.File, walkFileDescriptors(seen, fd)...) @@ -571,20 +572,24 @@ func (c *Client) convertToMethodInfo(fdset *descriptorpb.FileDescriptorSet) ([]M return rtn, nil } -func walkFileDescriptors(seen map[string]struct{}, fd *desc.FileDescriptor) []*descriptorpb.FileDescriptorProto { +// walkFileDescriptors recursively walks through a file descriptor and its dependencies, +// converting them to FileDescriptorProto. +// This ensures that all dependencies are included in the FileDescriptorSet. +func walkFileDescriptors(seen map[string]struct{}, fd protoreflect.FileDescriptor) []*descriptorpb.FileDescriptorProto { fds := []*descriptorpb.FileDescriptorProto{} - if _, ok := seen[fd.GetName()]; ok { + if _, ok := seen[fd.Path()]; ok { return fds } - seen[fd.GetName()] = struct{}{} - fds = append(fds, fd.AsFileDescriptorProto()) + seen[fd.Path()] = struct{}{} + fds = append(fds, protodesc.ToFileDescriptorProto(fd)) - for _, dep := range fd.GetDependencies() { + imports := fd.Imports() + for i := 0; i < imports.Len(); i++ { + dep := imports.Get(i).FileDescriptor deps := walkFileDescriptors(seen, dep) fds = append(fds, deps...) } - return fds } diff --git a/internal/lib/netext/grpcext/conn_test.go b/internal/lib/netext/grpcext/conn_test.go index 2fc1668c7..8fd4cd476 100644 --- a/internal/lib/netext/grpcext/conn_test.go +++ b/internal/lib/netext/grpcext/conn_test.go @@ -7,14 +7,13 @@ import ( "io" "testing" - "github.com/jhump/protoreflect/desc/protoparse" //nolint:staticcheck // FIXME: #4035 + "github.com/bufbuild/protocompile" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" - "google.golang.org/protobuf/reflect/protodesc" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/dynamicpb" @@ -252,9 +251,9 @@ func TestConnInvokeInvalid(t *testing.T) { func methodFromProto(method string) protoreflect.MethodDescriptor { path := "any-path" - parser := protoparse.Parser{ - InferImportPaths: false, - Accessor: protoparse.FileAccessor(func(filename string) (io.ReadCloser, error) { + + resolver := &protocompile.SourceResolver{ + Accessor: func(filename string) (io.ReadCloser, error) { // a small hack to make sure we are parsing the right file // otherwise the parser will try to parse "google/protobuf/descriptor.proto" // with exactly the same name as the one we are trying to parse for testing @@ -286,19 +285,23 @@ message HelloResponse { message Empty { }` + return io.NopCloser(bytes.NewBufferString(b)), nil - }), + }, } - fds, err := parser.ParseFiles(path) - if err != nil { - panic(err) + compiler := protocompile.Compiler{ + Resolver: resolver, } - fd, err := protodesc.NewFile(fds[0].AsFileDescriptorProto(), nil) + fds, err := compiler.Compile(context.Background(), path) if err != nil { panic(err) } + if len(fds) != 1 { + panic("expected exactly one file descriptor") + } + fd := fds[0] services := fd.Services() if services.Len() == 0 { diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast.go deleted file mode 100644 index 2b6b12442..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast.go +++ /dev/null @@ -1,716 +0,0 @@ -package protoparse - -import ( - "fmt" - - "github.com/bufbuild/protocompile/ast" - - ast2 "github.com/jhump/protoreflect/desc/protoparse/ast" -) - -func convertAST(file *ast.FileNode) *ast2.FileNode { - elements := make([]ast2.FileElement, len(file.Decls)) - for i := range file.Decls { - elements[i] = convertASTFileElement(file, file.Decls[i]) - } - root := ast2.NewFileNode(convertASTSyntax(file, file.Syntax), elements) - eofInfo := file.NodeInfo(file.EOF) - root.FinalComments = convertASTComments(eofInfo.LeadingComments()) - root.FinalWhitespace = eofInfo.LeadingWhitespace() - return root -} - -func convertASTSyntax(f *ast.FileNode, s *ast.SyntaxNode) *ast2.SyntaxNode { - return ast2.NewSyntaxNode( - convertASTKeyword(f, s.Keyword), - convertASTRune(f, s.Equals), - convertASTString(f, s.Syntax), - convertASTRune(f, s.Semicolon), - ) -} - -func convertASTFileElement(f *ast.FileNode, el ast.FileElement) ast2.FileElement { - switch el := el.(type) { - case *ast.ImportNode: - return convertASTImport(f, el) - case *ast.PackageNode: - return convertASTPackage(f, el) - case *ast.OptionNode: - return convertASTOption(f, el) - case *ast.MessageNode: - return convertASTMessage(f, el) - case *ast.EnumNode: - return convertASTEnum(f, el) - case *ast.ExtendNode: - return convertASTExtend(f, el) - case *ast.ServiceNode: - return convertASTService(f, el) - case *ast.EmptyDeclNode: - return convertASTEmpty(f, el) - default: - panic(fmt.Sprintf("unrecognized type of ast.FileElement: %T", el)) - } -} - -func convertASTImport(f *ast.FileNode, imp *ast.ImportNode) *ast2.ImportNode { - var public, weak *ast2.KeywordNode - if imp.Public != nil { - public = convertASTKeyword(f, imp.Public) - } - if imp.Weak != nil { - weak = convertASTKeyword(f, imp.Weak) - } - return ast2.NewImportNode( - convertASTKeyword(f, imp.Keyword), - public, weak, - convertASTString(f, imp.Name), - convertASTRune(f, imp.Semicolon), - ) -} - -func convertASTPackage(f *ast.FileNode, p *ast.PackageNode) *ast2.PackageNode { - return ast2.NewPackageNode( - convertASTKeyword(f, p.Keyword), - convertASTIdent(f, p.Name), - convertASTRune(f, p.Semicolon), - ) -} - -func convertASTOption(f *ast.FileNode, o *ast.OptionNode) *ast2.OptionNode { - if o.Keyword == nil { - return ast2.NewCompactOptionNode( - convertASTOptionName(f, o.Name), - convertASTRune(f, o.Equals), - convertASTValue(f, o.Val), - ) - } - return ast2.NewOptionNode( - convertASTKeyword(f, o.Keyword), - convertASTOptionName(f, o.Name), - convertASTRune(f, o.Equals), - convertASTValue(f, o.Val), - convertASTRune(f, o.Semicolon), - ) -} - -func convertASTOptionName(f *ast.FileNode, n *ast.OptionNameNode) *ast2.OptionNameNode { - parts := make([]*ast2.FieldReferenceNode, len(n.Parts)) - for i := range n.Parts { - parts[i] = convertASTFieldReference(f, n.Parts[i]) - } - dots := make([]*ast2.RuneNode, len(n.Dots)) - for i := range n.Dots { - dots[i] = convertASTRune(f, n.Dots[i]) - } - return ast2.NewOptionNameNode(parts, dots) -} - -func convertASTFieldReference(f *ast.FileNode, n *ast.FieldReferenceNode) *ast2.FieldReferenceNode { - switch { - case n.IsExtension(): - return ast2.NewExtensionFieldReferenceNode( - convertASTRune(f, n.Open), - convertASTIdent(f, n.Name), - convertASTRune(f, n.Close), - ) - case n.IsAnyTypeReference(): - return ast2.NewAnyTypeReferenceNode( - convertASTRune(f, n.Open), - convertASTIdent(f, n.URLPrefix), - convertASTRune(f, n.Slash), - convertASTIdent(f, n.Name), - convertASTRune(f, n.Close), - ) - default: - return ast2.NewFieldReferenceNode(convertASTIdent(f, n.Name).(*ast2.IdentNode)) - } -} - -func convertASTMessage(f *ast.FileNode, m *ast.MessageNode) *ast2.MessageNode { - decls := make([]ast2.MessageElement, len(m.Decls)) - for i := range m.Decls { - decls[i] = convertASTMessageElement(f, m.Decls[i]) - } - return ast2.NewMessageNode( - convertASTKeyword(f, m.Keyword), - convertASTIdentToken(f, m.Name), - convertASTRune(f, m.OpenBrace), - decls, - convertASTRune(f, m.CloseBrace), - ) -} - -func convertASTMessageElement(f *ast.FileNode, el ast.MessageElement) ast2.MessageElement { - switch el := el.(type) { - case *ast.OptionNode: - return convertASTOption(f, el) - case *ast.FieldNode: - return convertASTField(f, el) - case *ast.MapFieldNode: - return convertASTMapField(f, el) - case *ast.OneofNode: - return convertASTOneOf(f, el) - case *ast.GroupNode: - return convertASTGroup(f, el) - case *ast.MessageNode: - return convertASTMessage(f, el) - case *ast.EnumNode: - return convertASTEnum(f, el) - case *ast.ExtendNode: - return convertASTExtend(f, el) - case *ast.ExtensionRangeNode: - return convertASTExtensions(f, el) - case *ast.ReservedNode: - return convertASTReserved(f, el) - case *ast.EmptyDeclNode: - return convertASTEmpty(f, el) - default: - panic(fmt.Sprintf("unrecognized type of ast.MessageElement: %T", el)) - } -} - -func convertASTField(f *ast.FileNode, fld *ast.FieldNode) *ast2.FieldNode { - var lbl *ast2.KeywordNode - if fld.Label.KeywordNode != nil { - lbl = convertASTKeyword(f, fld.Label.KeywordNode) - } - var opts *ast2.CompactOptionsNode - if fld.Options != nil { - opts = convertASTCompactOptions(f, fld.Options) - } - return ast2.NewFieldNode( - lbl, - convertASTIdent(f, fld.FldType), - convertASTIdentToken(f, fld.Name), - convertASTRune(f, fld.Equals), - convertASTUintLiteral(f, fld.Tag), - opts, - convertASTRune(f, fld.Semicolon), - ) -} - -func convertASTMapField(f *ast.FileNode, fld *ast.MapFieldNode) *ast2.MapFieldNode { - var opts *ast2.CompactOptionsNode - if fld.Options != nil { - opts = convertASTCompactOptions(f, fld.Options) - } - return ast2.NewMapFieldNode( - convertASTMapFieldType(f, fld.MapType), - convertASTIdentToken(f, fld.Name), - convertASTRune(f, fld.Equals), - convertASTUintLiteral(f, fld.Tag), - opts, - convertASTRune(f, fld.Semicolon), - ) -} - -func convertASTMapFieldType(f *ast.FileNode, t *ast.MapTypeNode) *ast2.MapTypeNode { - return ast2.NewMapTypeNode( - convertASTKeyword(f, t.Keyword), - convertASTRune(f, t.OpenAngle), - convertASTIdentToken(f, t.KeyType), - convertASTRune(f, t.Comma), - convertASTIdent(f, t.ValueType), - convertASTRune(f, t.CloseAngle), - ) -} - -func convertASTGroup(f *ast.FileNode, g *ast.GroupNode) *ast2.GroupNode { - var lbl *ast2.KeywordNode - if g.Label.KeywordNode != nil { - lbl = convertASTKeyword(f, g.Label.KeywordNode) - } - var opts *ast2.CompactOptionsNode - if g.Options != nil { - opts = convertASTCompactOptions(f, g.Options) - } - decls := make([]ast2.MessageElement, len(g.Decls)) - for i := range g.Decls { - decls[i] = convertASTMessageElement(f, g.Decls[i]) - } - return ast2.NewGroupNode( - lbl, - convertASTKeyword(f, g.Keyword), - convertASTIdentToken(f, g.Name), - convertASTRune(f, g.Equals), - convertASTUintLiteral(f, g.Tag), - opts, - convertASTRune(f, g.OpenBrace), - decls, - convertASTRune(f, g.CloseBrace), - ) -} - -func convertASTOneOf(f *ast.FileNode, oo *ast.OneofNode) *ast2.OneOfNode { - decls := make([]ast2.OneOfElement, len(oo.Decls)) - for i := range oo.Decls { - decls[i] = convertASTOneOfElement(f, oo.Decls[i]) - } - return ast2.NewOneOfNode( - convertASTKeyword(f, oo.Keyword), - convertASTIdentToken(f, oo.Name), - convertASTRune(f, oo.OpenBrace), - decls, - convertASTRune(f, oo.CloseBrace), - ) -} - -func convertASTOneOfElement(f *ast.FileNode, el ast.OneofElement) ast2.OneOfElement { - switch el := el.(type) { - case *ast.OptionNode: - return convertASTOption(f, el) - case *ast.FieldNode: - return convertASTField(f, el) - case *ast.GroupNode: - return convertASTGroup(f, el) - case *ast.EmptyDeclNode: - return convertASTEmpty(f, el) - default: - panic(fmt.Sprintf("unrecognized type of ast.OneOfElement: %T", el)) - } -} - -func convertASTExtensions(f *ast.FileNode, e *ast.ExtensionRangeNode) *ast2.ExtensionRangeNode { - var opts *ast2.CompactOptionsNode - if e.Options != nil { - opts = convertASTCompactOptions(f, e.Options) - } - ranges := make([]*ast2.RangeNode, len(e.Ranges)) - for i := range e.Ranges { - ranges[i] = convertASTRange(f, e.Ranges[i]) - } - commas := make([]*ast2.RuneNode, len(e.Commas)) - for i := range e.Commas { - commas[i] = convertASTRune(f, e.Commas[i]) - } - return ast2.NewExtensionRangeNode( - convertASTKeyword(f, e.Keyword), - ranges, commas, opts, - convertASTRune(f, e.Semicolon), - ) -} - -func convertASTReserved(f *ast.FileNode, r *ast.ReservedNode) *ast2.ReservedNode { - ranges := make([]*ast2.RangeNode, len(r.Ranges)) - for i := range r.Ranges { - ranges[i] = convertASTRange(f, r.Ranges[i]) - } - commas := make([]*ast2.RuneNode, len(r.Commas)) - for i := range r.Commas { - commas[i] = convertASTRune(f, r.Commas[i]) - } - names := make([]ast2.StringValueNode, len(r.Names)) - for i := range r.Names { - names[i] = convertASTString(f, r.Names[i]) - } - if len(r.Ranges) > 0 { - return ast2.NewReservedRangesNode( - convertASTKeyword(f, r.Keyword), - ranges, commas, - convertASTRune(f, r.Semicolon), - ) - } - return ast2.NewReservedNamesNode( - convertASTKeyword(f, r.Keyword), - names, commas, - convertASTRune(f, r.Semicolon), - ) -} - -func convertASTRange(f *ast.FileNode, r *ast.RangeNode) *ast2.RangeNode { - var to, max *ast2.KeywordNode - var end ast2.IntValueNode - if r.To != nil { - to = convertASTKeyword(f, r.To) - } - if r.Max != nil { - max = convertASTKeyword(f, r.Max) - } - if r.EndVal != nil { - end = convertASTInt(f, r.EndVal) - } - return ast2.NewRangeNode( - convertASTInt(f, r.StartVal), - to, end, max, - ) -} - -func convertASTEnum(f *ast.FileNode, e *ast.EnumNode) *ast2.EnumNode { - decls := make([]ast2.EnumElement, len(e.Decls)) - for i := range e.Decls { - decls[i] = convertASTEnumElement(f, e.Decls[i]) - } - return ast2.NewEnumNode( - convertASTKeyword(f, e.Keyword), - convertASTIdentToken(f, e.Name), - convertASTRune(f, e.OpenBrace), - decls, - convertASTRune(f, e.CloseBrace), - ) -} - -func convertASTEnumElement(f *ast.FileNode, el ast.EnumElement) ast2.EnumElement { - switch el := el.(type) { - case *ast.OptionNode: - return convertASTOption(f, el) - case *ast.EnumValueNode: - return convertASTEnumValue(f, el) - case *ast.ReservedNode: - return convertASTReserved(f, el) - case *ast.EmptyDeclNode: - return convertASTEmpty(f, el) - default: - panic(fmt.Sprintf("unrecognized type of ast.EnumElement: %T", el)) - } -} - -func convertASTEnumValue(f *ast.FileNode, e *ast.EnumValueNode) *ast2.EnumValueNode { - var opts *ast2.CompactOptionsNode - if e.Options != nil { - opts = convertASTCompactOptions(f, e.Options) - } - return ast2.NewEnumValueNode( - convertASTIdentToken(f, e.Name), - convertASTRune(f, e.Equals), - convertASTInt(f, e.Number), - opts, - convertASTRune(f, e.Semicolon), - ) -} - -func convertASTExtend(f *ast.FileNode, e *ast.ExtendNode) *ast2.ExtendNode { - decls := make([]ast2.ExtendElement, len(e.Decls)) - for i := range e.Decls { - decls[i] = convertASTExtendElement(f, e.Decls[i]) - } - return ast2.NewExtendNode( - convertASTKeyword(f, e.Keyword), - convertASTIdent(f, e.Extendee), - convertASTRune(f, e.OpenBrace), - decls, - convertASTRune(f, e.CloseBrace), - ) -} - -func convertASTExtendElement(f *ast.FileNode, el ast.ExtendElement) ast2.ExtendElement { - switch el := el.(type) { - case *ast.FieldNode: - return convertASTField(f, el) - case *ast.GroupNode: - return convertASTGroup(f, el) - case *ast.EmptyDeclNode: - return convertASTEmpty(f, el) - default: - panic(fmt.Sprintf("unrecognized type of ast.ExtendElement: %T", el)) - } -} - -func convertASTService(f *ast.FileNode, s *ast.ServiceNode) *ast2.ServiceNode { - decls := make([]ast2.ServiceElement, len(s.Decls)) - for i := range s.Decls { - decls[i] = convertASTServiceElement(f, s.Decls[i]) - } - return ast2.NewServiceNode( - convertASTKeyword(f, s.Keyword), - convertASTIdentToken(f, s.Name), - convertASTRune(f, s.OpenBrace), - decls, - convertASTRune(f, s.CloseBrace), - ) -} - -func convertASTServiceElement(f *ast.FileNode, el ast.ServiceElement) ast2.ServiceElement { - switch el := el.(type) { - case *ast.OptionNode: - return convertASTOption(f, el) - case *ast.RPCNode: - return convertASTMethod(f, el) - case *ast.EmptyDeclNode: - return convertASTEmpty(f, el) - default: - panic(fmt.Sprintf("unrecognized type of ast.ServiceElement: %T", el)) - } -} - -func convertASTMethod(f *ast.FileNode, m *ast.RPCNode) *ast2.RPCNode { - if m.OpenBrace == nil { - return ast2.NewRPCNode( - convertASTKeyword(f, m.Keyword), - convertASTIdentToken(f, m.Name), - convertASTMethodType(f, m.Input), - convertASTKeyword(f, m.Returns), - convertASTMethodType(f, m.Output), - convertASTRune(f, m.Semicolon), - ) - } - decls := make([]ast2.RPCElement, len(m.Decls)) - for i := range m.Decls { - decls[i] = convertASTMethodElement(f, m.Decls[i]) - } - return ast2.NewRPCNodeWithBody( - convertASTKeyword(f, m.Keyword), - convertASTIdentToken(f, m.Name), - convertASTMethodType(f, m.Input), - convertASTKeyword(f, m.Returns), - convertASTMethodType(f, m.Output), - convertASTRune(f, m.OpenBrace), - decls, - convertASTRune(f, m.CloseBrace), - ) -} - -func convertASTMethodElement(f *ast.FileNode, el ast.RPCElement) ast2.RPCElement { - switch el := el.(type) { - case *ast.OptionNode: - return convertASTOption(f, el) - case *ast.EmptyDeclNode: - return convertASTEmpty(f, el) - default: - panic(fmt.Sprintf("unrecognized type of ast.RPCElement: %T", el)) - } -} - -func convertASTMethodType(f *ast.FileNode, t *ast.RPCTypeNode) *ast2.RPCTypeNode { - var stream *ast2.KeywordNode - if t.Stream != nil { - stream = convertASTKeyword(f, t.Stream) - } - return ast2.NewRPCTypeNode( - convertASTRune(f, t.OpenParen), - stream, - convertASTIdent(f, t.MessageType), - convertASTRune(f, t.CloseParen), - ) -} - -func convertASTCompactOptions(f *ast.FileNode, opts *ast.CompactOptionsNode) *ast2.CompactOptionsNode { - elems := make([]*ast2.OptionNode, len(opts.Options)) - for i := range opts.Options { - elems[i] = convertASTOption(f, opts.Options[i]) - } - commas := make([]*ast2.RuneNode, len(opts.Commas)) - for i := range opts.Commas { - commas[i] = convertASTRune(f, opts.Commas[i]) - } - return ast2.NewCompactOptionsNode( - convertASTRune(f, opts.OpenBracket), - elems, commas, - convertASTRune(f, opts.CloseBracket), - ) -} - -func convertASTEmpty(f *ast.FileNode, e *ast.EmptyDeclNode) *ast2.EmptyDeclNode { - return ast2.NewEmptyDeclNode(convertASTRune(f, e.Semicolon)) -} - -func convertASTValue(f *ast.FileNode, v ast.ValueNode) ast2.ValueNode { - switch v := v.(type) { - case *ast.IdentNode: - return convertASTIdentToken(f, v) - case *ast.CompoundIdentNode: - return convertASTCompoundIdent(f, v) - case *ast.StringLiteralNode: - return convertASTStringLiteral(f, v) - case *ast.CompoundStringLiteralNode: - return convertASTCompoundStringLiteral(f, v) - case *ast.UintLiteralNode: - return convertASTUintLiteral(f, v) - case *ast.NegativeIntLiteralNode: - return convertASTNegativeIntLiteral(f, v) - case *ast.FloatLiteralNode: - return convertASTFloatLiteral(f, v) - case *ast.SpecialFloatLiteralNode: - return convertASTSpecialFloatLiteral(f, v) - case *ast.SignedFloatLiteralNode: - return convertASTSignedFloatLiteral(f, v) - case *ast.ArrayLiteralNode: - return convertASTArrayLiteral(f, v) - case *ast.MessageLiteralNode: - return convertASTMessageLiteral(f, v) - default: - panic(fmt.Sprintf("unrecognized type of ast.ValueNode: %T", v)) - } -} - -func convertASTIdent(f *ast.FileNode, ident ast.IdentValueNode) ast2.IdentValueNode { - switch ident := ident.(type) { - case *ast.IdentNode: - return convertASTIdentToken(f, ident) - case *ast.CompoundIdentNode: - return convertASTCompoundIdent(f, ident) - default: - panic(fmt.Sprintf("unrecognized type of ast.IdentValueNode: %T", ident)) - } -} - -func convertASTIdentToken(f *ast.FileNode, ident *ast.IdentNode) *ast2.IdentNode { - return ast2.NewIdentNode(ident.Val, convertASTTokenInfo(f, ident.Token())) -} - -func convertASTCompoundIdent(f *ast.FileNode, ident *ast.CompoundIdentNode) *ast2.CompoundIdentNode { - var leadingDot *ast2.RuneNode - if ident.LeadingDot != nil { - leadingDot = convertASTRune(f, ident.LeadingDot) - } - components := make([]*ast2.IdentNode, len(ident.Components)) - for i := range ident.Components { - components[i] = convertASTIdentToken(f, ident.Components[i]) - } - dots := make([]*ast2.RuneNode, len(ident.Dots)) - for i := range ident.Dots { - dots[i] = convertASTRune(f, ident.Dots[i]) - } - return ast2.NewCompoundIdentNode(leadingDot, components, dots) -} - -func convertASTString(f *ast.FileNode, str ast.StringValueNode) ast2.StringValueNode { - switch str := str.(type) { - case *ast.StringLiteralNode: - return convertASTStringLiteral(f, str) - case *ast.CompoundStringLiteralNode: - return convertASTCompoundStringLiteral(f, str) - default: - panic(fmt.Sprintf("unrecognized type of ast.StringValueNode: %T", str)) - } -} - -func convertASTStringLiteral(f *ast.FileNode, str *ast.StringLiteralNode) *ast2.StringLiteralNode { - return ast2.NewStringLiteralNode(str.Val, convertASTTokenInfo(f, str.Token())) -} - -func convertASTCompoundStringLiteral(f *ast.FileNode, str *ast.CompoundStringLiteralNode) *ast2.CompoundStringLiteralNode { - children := str.Children() - components := make([]*ast2.StringLiteralNode, len(children)) - for i := range children { - components[i] = convertASTStringLiteral(f, children[i].(*ast.StringLiteralNode)) - } - return ast2.NewCompoundLiteralStringNode(components...) -} - -func convertASTInt(f *ast.FileNode, n ast.IntValueNode) ast2.IntValueNode { - switch n := n.(type) { - case *ast.UintLiteralNode: - return convertASTUintLiteral(f, n) - case *ast.NegativeIntLiteralNode: - return convertASTNegativeIntLiteral(f, n) - default: - panic(fmt.Sprintf("unrecognized type of ast.IntValueNode: %T", n)) - } -} - -func convertASTUintLiteral(f *ast.FileNode, n *ast.UintLiteralNode) *ast2.UintLiteralNode { - return ast2.NewUintLiteralNode(n.Val, convertASTTokenInfo(f, n.Token())) -} - -func convertASTNegativeIntLiteral(f *ast.FileNode, n *ast.NegativeIntLiteralNode) *ast2.NegativeIntLiteralNode { - return ast2.NewNegativeIntLiteralNode(convertASTRune(f, n.Minus), convertASTUintLiteral(f, n.Uint)) -} - -func convertASTFloat(f *ast.FileNode, n ast.FloatValueNode) ast2.FloatValueNode { - switch n := n.(type) { - case *ast.FloatLiteralNode: - return convertASTFloatLiteral(f, n) - case *ast.SpecialFloatLiteralNode: - return convertASTSpecialFloatLiteral(f, n) - case *ast.UintLiteralNode: - return convertASTUintLiteral(f, n) - default: - panic(fmt.Sprintf("unrecognized type of ast.FloatValueNode: %T", n)) - } -} - -func convertASTFloatLiteral(f *ast.FileNode, n *ast.FloatLiteralNode) *ast2.FloatLiteralNode { - return ast2.NewFloatLiteralNode(n.Val, convertASTTokenInfo(f, n.Token())) -} - -func convertASTSpecialFloatLiteral(f *ast.FileNode, n *ast.SpecialFloatLiteralNode) *ast2.SpecialFloatLiteralNode { - return ast2.NewSpecialFloatLiteralNode(convertASTKeyword(f, n.KeywordNode)) -} - -func convertASTSignedFloatLiteral(f *ast.FileNode, n *ast.SignedFloatLiteralNode) *ast2.SignedFloatLiteralNode { - return ast2.NewSignedFloatLiteralNode(convertASTRune(f, n.Sign), convertASTFloat(f, n.Float)) -} - -func convertASTArrayLiteral(f *ast.FileNode, ar *ast.ArrayLiteralNode) *ast2.ArrayLiteralNode { - vals := make([]ast2.ValueNode, len(ar.Elements)) - for i := range ar.Elements { - vals[i] = convertASTValue(f, ar.Elements[i]) - } - commas := make([]*ast2.RuneNode, len(ar.Commas)) - for i := range ar.Commas { - commas[i] = convertASTRune(f, ar.Commas[i]) - } - return ast2.NewArrayLiteralNode( - convertASTRune(f, ar.OpenBracket), - vals, commas, - convertASTRune(f, ar.CloseBracket), - ) -} - -func convertASTMessageLiteral(f *ast.FileNode, m *ast.MessageLiteralNode) *ast2.MessageLiteralNode { - fields := make([]*ast2.MessageFieldNode, len(m.Elements)) - for i := range m.Elements { - fields[i] = convertASTMessageLiteralField(f, m.Elements[i]) - } - seps := make([]*ast2.RuneNode, len(m.Seps)) - for i := range m.Seps { - if m.Seps[i] != nil { - seps[i] = convertASTRune(f, m.Seps[i]) - } - } - return ast2.NewMessageLiteralNode( - convertASTRune(f, m.Open), - fields, seps, - convertASTRune(f, m.Close), - ) -} - -func convertASTMessageLiteralField(f *ast.FileNode, fld *ast.MessageFieldNode) *ast2.MessageFieldNode { - var sep *ast2.RuneNode - if fld.Sep != nil { - sep = convertASTRune(f, fld.Sep) - } - return ast2.NewMessageFieldNode( - convertASTFieldReference(f, fld.Name), - sep, - convertASTValue(f, fld.Val), - ) -} - -func convertASTKeyword(f *ast.FileNode, k *ast.KeywordNode) *ast2.KeywordNode { - return ast2.NewKeywordNode(k.Val, convertASTTokenInfo(f, k.Token())) -} - -func convertASTRune(f *ast.FileNode, r *ast.RuneNode) *ast2.RuneNode { - return ast2.NewRuneNode(r.Rune, convertASTTokenInfo(f, r.Token())) -} - -func convertASTTokenInfo(f *ast.FileNode, tok ast.Token) ast2.TokenInfo { - info := f.TokenInfo(tok) - return ast2.TokenInfo{ - PosRange: ast2.PosRange{ - Start: info.Start(), - End: info.End(), - }, - RawText: info.RawText(), - LeadingWhitespace: info.LeadingWhitespace(), - LeadingComments: convertASTComments(info.LeadingComments()), - TrailingComments: convertASTComments(info.TrailingComments()), - } -} - -func convertASTComments(comments ast.Comments) []ast2.Comment { - results := make([]ast2.Comment, comments.Len()) - for i := 0; i < comments.Len(); i++ { - cmt := comments.Index(i) - results[i] = ast2.Comment{ - PosRange: ast2.PosRange{ - Start: cmt.Start(), - End: cmt.End(), - }, - LeadingWhitespace: cmt.LeadingWhitespace(), - Text: cmt.RawText(), - } - } - return results -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/doc.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/doc.go deleted file mode 100644 index e8902000a..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/doc.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package ast defines types for modeling the AST (Abstract Syntax -// Tree) for the protocol buffers source language. -// -// All nodes of the tree implement the Node interface. Leaf nodes in the -// tree implement TerminalNode and all others implement CompositeNode. -// The root of the tree for a proto source file is a *FileNode. -// -// Comments are not represented as nodes in the tree. Instead, they are -// attached to all terminal nodes in the tree. So, when lexing, comments -// are accumulated until the next non-comment token is found. The AST -// model in this package thus provides access to all comments in the -// file, regardless of location (unlike the SourceCodeInfo present in -// descriptor protos, which are lossy). The comments associated with a -// a non-leaf/non-token node (i.e. a CompositeNode) come from the first -// and last nodes in its sub-tree. -// -// Creation of AST nodes should use the factory functions in this -// package instead of struct literals. Some factory functions accept -// optional arguments, which means the arguments can be nil. If nil -// values are provided for other (non-optional) arguments, the resulting -// node may be invalid and cause panics later in the program. -// -// This package defines numerous interfaces. However, user code should -// not attempt to implement any of them. Most consumers of an AST will -// not work correctly if they encounter concrete implementations other -// than the ones defined in this package. -package ast diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/enum.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/enum.go deleted file mode 100644 index 446a6a013..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/enum.go +++ /dev/null @@ -1,154 +0,0 @@ -package ast - -import "fmt" - -// EnumNode represents an enum declaration. Example: -// -// enum Foo { BAR = 0; BAZ = 1 } -type EnumNode struct { - compositeNode - Keyword *KeywordNode - Name *IdentNode - OpenBrace *RuneNode - Decls []EnumElement - CloseBrace *RuneNode -} - -func (*EnumNode) fileElement() {} -func (*EnumNode) msgElement() {} - -// NewEnumNode creates a new *EnumNode. All arguments must be non-nil. While -// it is technically allowed for decls to be nil or empty, the resulting node -// will not be a valid enum, which must have at least one value. -// - keyword: The token corresponding to the "enum" keyword. -// - name: The token corresponding to the enum's name. -// - openBrace: The token corresponding to the "{" rune that starts the body. -// - decls: All declarations inside the enum body. -// - closeBrace: The token corresponding to the "}" rune that ends the body. -func NewEnumNode(keyword *KeywordNode, name *IdentNode, openBrace *RuneNode, decls []EnumElement, closeBrace *RuneNode) *EnumNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if openBrace == nil { - panic("openBrace is nil") - } - if closeBrace == nil { - panic("closeBrace is nil") - } - children := make([]Node, 0, 4+len(decls)) - children = append(children, keyword, name, openBrace) - for _, decl := range decls { - children = append(children, decl) - } - children = append(children, closeBrace) - - for _, decl := range decls { - switch decl.(type) { - case *OptionNode, *EnumValueNode, *ReservedNode, *EmptyDeclNode: - default: - panic(fmt.Sprintf("invalid EnumElement type: %T", decl)) - } - } - - return &EnumNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Name: name, - OpenBrace: openBrace, - CloseBrace: closeBrace, - Decls: decls, - } -} - -// EnumElement is an interface implemented by all AST nodes that can -// appear in the body of an enum declaration. -type EnumElement interface { - Node - enumElement() -} - -var _ EnumElement = (*OptionNode)(nil) -var _ EnumElement = (*EnumValueNode)(nil) -var _ EnumElement = (*ReservedNode)(nil) -var _ EnumElement = (*EmptyDeclNode)(nil) - -// EnumValueDeclNode is a placeholder interface for AST nodes that represent -// enum values. This allows NoSourceNode to be used in place of *EnumValueNode -// for some usages. -type EnumValueDeclNode interface { - Node - GetName() Node - GetNumber() Node -} - -var _ EnumValueDeclNode = (*EnumValueNode)(nil) -var _ EnumValueDeclNode = NoSourceNode{} - -// EnumNode represents an enum declaration. Example: -// -// UNSET = 0 [deprecated = true]; -type EnumValueNode struct { - compositeNode - Name *IdentNode - Equals *RuneNode - Number IntValueNode - Options *CompactOptionsNode - Semicolon *RuneNode -} - -func (*EnumValueNode) enumElement() {} - -// NewEnumValueNode creates a new *EnumValueNode. All arguments must be non-nil -// except opts which is only non-nil if the declaration included options. -// - name: The token corresponding to the enum value's name. -// - equals: The token corresponding to the '=' rune after the name. -// - number: The token corresponding to the enum value's number. -// - opts: Optional set of enum value options. -// - semicolon: The token corresponding to the ";" rune that ends the declaration. -func NewEnumValueNode(name *IdentNode, equals *RuneNode, number IntValueNode, opts *CompactOptionsNode, semicolon *RuneNode) *EnumValueNode { - if name == nil { - panic("name is nil") - } - if equals == nil { - panic("equals is nil") - } - if number == nil { - panic("number is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - numChildren := 4 - if opts != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - children = append(children, name, equals, number) - if opts != nil { - children = append(children, opts) - } - children = append(children, semicolon) - return &EnumValueNode{ - compositeNode: compositeNode{ - children: children, - }, - Name: name, - Equals: equals, - Number: number, - Options: opts, - Semicolon: semicolon, - } -} - -func (e *EnumValueNode) GetName() Node { - return e.Name -} - -func (e *EnumValueNode) GetNumber() Node { - return e.Number -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/field.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/field.go deleted file mode 100644 index 7ec9391bb..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/field.go +++ /dev/null @@ -1,659 +0,0 @@ -package ast - -import "fmt" - -// FieldDeclNode is a node in the AST that defines a field. This includes -// normal message fields as well as extensions. There are multiple types -// of AST nodes that declare fields: -// - *FieldNode -// - *GroupNode -// - *MapFieldNode -// - *SyntheticMapField -// -// This also allows NoSourceNode to be used in place of one of the above -// for some usages. -type FieldDeclNode interface { - Node - FieldLabel() Node - FieldName() Node - FieldType() Node - FieldTag() Node - FieldExtendee() Node - GetGroupKeyword() Node - GetOptions() *CompactOptionsNode -} - -var _ FieldDeclNode = (*FieldNode)(nil) -var _ FieldDeclNode = (*GroupNode)(nil) -var _ FieldDeclNode = (*MapFieldNode)(nil) -var _ FieldDeclNode = (*SyntheticMapField)(nil) -var _ FieldDeclNode = NoSourceNode{} - -// FieldNode represents a normal field declaration (not groups or maps). It -// can represent extension fields as well as non-extension fields (both inside -// of messages and inside of one-ofs). Example: -// -// optional string foo = 1; -type FieldNode struct { - compositeNode - Label FieldLabel - FldType IdentValueNode - Name *IdentNode - Equals *RuneNode - Tag *UintLiteralNode - Options *CompactOptionsNode - Semicolon *RuneNode - - // This is an up-link to the containing *ExtendNode for fields - // that are defined inside of "extend" blocks. - Extendee *ExtendNode -} - -func (*FieldNode) msgElement() {} -func (*FieldNode) oneOfElement() {} -func (*FieldNode) extendElement() {} - -// NewFieldNode creates a new *FieldNode. The label and options arguments may be -// nil but the others must be non-nil. -// - label: The token corresponding to the label keyword if present ("optional", -// "required", or "repeated"). -// - fieldType: The token corresponding to the field's type. -// - name: The token corresponding to the field's name. -// - equals: The token corresponding to the '=' rune after the name. -// - tag: The token corresponding to the field's tag number. -// - opts: Optional set of field options. -// - semicolon: The token corresponding to the ";" rune that ends the declaration. -func NewFieldNode(label *KeywordNode, fieldType IdentValueNode, name *IdentNode, equals *RuneNode, tag *UintLiteralNode, opts *CompactOptionsNode, semicolon *RuneNode) *FieldNode { - if fieldType == nil { - panic("fieldType is nil") - } - if name == nil { - panic("name is nil") - } - if equals == nil { - panic("equals is nil") - } - if tag == nil { - panic("tag is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - numChildren := 5 - if label != nil { - numChildren++ - } - if opts != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - if label != nil { - children = append(children, label) - } - children = append(children, fieldType, name, equals, tag) - if opts != nil { - children = append(children, opts) - } - children = append(children, semicolon) - - return &FieldNode{ - compositeNode: compositeNode{ - children: children, - }, - Label: newFieldLabel(label), - FldType: fieldType, - Name: name, - Equals: equals, - Tag: tag, - Options: opts, - Semicolon: semicolon, - } -} - -func (n *FieldNode) FieldLabel() Node { - // proto3 fields and fields inside one-ofs will not have a label and we need - // this check in order to return a nil node -- otherwise we'd return a - // non-nil node that has a nil pointer value in it :/ - if n.Label.KeywordNode == nil { - return nil - } - return n.Label.KeywordNode -} - -func (n *FieldNode) FieldName() Node { - return n.Name -} - -func (n *FieldNode) FieldType() Node { - return n.FldType -} - -func (n *FieldNode) FieldTag() Node { - return n.Tag -} - -func (n *FieldNode) FieldExtendee() Node { - if n.Extendee != nil { - return n.Extendee.Extendee - } - return nil -} - -func (n *FieldNode) GetGroupKeyword() Node { - return nil -} - -func (n *FieldNode) GetOptions() *CompactOptionsNode { - return n.Options -} - -// FieldLabel represents the label of a field, which indicates its cardinality -// (i.e. whether it is optional, required, or repeated). -type FieldLabel struct { - *KeywordNode - Repeated bool - Required bool -} - -func newFieldLabel(lbl *KeywordNode) FieldLabel { - repeated, required := false, false - if lbl != nil { - repeated = lbl.Val == "repeated" - required = lbl.Val == "required" - } - return FieldLabel{ - KeywordNode: lbl, - Repeated: repeated, - Required: required, - } -} - -// IsPresent returns true if a label keyword was present in the declaration -// and false if it was absent. -func (f *FieldLabel) IsPresent() bool { - return f.KeywordNode != nil -} - -// GroupNode represents a group declaration, which doubles as a field and inline -// message declaration. It can represent extension fields as well as -// non-extension fields (both inside of messages and inside of one-ofs). -// Example: -// -// optional group Key = 4 { -// optional uint64 id = 1; -// optional string name = 2; -// } -type GroupNode struct { - compositeNode - Label FieldLabel - Keyword *KeywordNode - Name *IdentNode - Equals *RuneNode - Tag *UintLiteralNode - Options *CompactOptionsNode - MessageBody - - // This is an up-link to the containing *ExtendNode for groups - // that are defined inside of "extend" blocks. - Extendee *ExtendNode -} - -func (*GroupNode) msgElement() {} -func (*GroupNode) oneOfElement() {} -func (*GroupNode) extendElement() {} - -// NewGroupNode creates a new *GroupNode. The label and options arguments may be -// nil but the others must be non-nil. -// - label: The token corresponding to the label keyword if present ("optional", -// "required", or "repeated"). -// - keyword: The token corresponding to the "group" keyword. -// - name: The token corresponding to the field's name. -// - equals: The token corresponding to the '=' rune after the name. -// - tag: The token corresponding to the field's tag number. -// - opts: Optional set of field options. -// - openBrace: The token corresponding to the "{" rune that starts the body. -// - decls: All declarations inside the group body. -// - closeBrace: The token corresponding to the "}" rune that ends the body. -func NewGroupNode(label *KeywordNode, keyword *KeywordNode, name *IdentNode, equals *RuneNode, tag *UintLiteralNode, opts *CompactOptionsNode, openBrace *RuneNode, decls []MessageElement, closeBrace *RuneNode) *GroupNode { - if keyword == nil { - panic("fieldType is nil") - } - if name == nil { - panic("name is nil") - } - if equals == nil { - panic("equals is nil") - } - if tag == nil { - panic("tag is nil") - } - if openBrace == nil { - panic("openBrace is nil") - } - if closeBrace == nil { - panic("closeBrace is nil") - } - numChildren := 6 + len(decls) - if label != nil { - numChildren++ - } - if opts != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - if label != nil { - children = append(children, label) - } - children = append(children, keyword, name, equals, tag) - if opts != nil { - children = append(children, opts) - } - children = append(children, openBrace) - for _, decl := range decls { - children = append(children, decl) - } - children = append(children, closeBrace) - - ret := &GroupNode{ - compositeNode: compositeNode{ - children: children, - }, - Label: newFieldLabel(label), - Keyword: keyword, - Name: name, - Equals: equals, - Tag: tag, - Options: opts, - } - populateMessageBody(&ret.MessageBody, openBrace, decls, closeBrace) - return ret -} - -func (n *GroupNode) FieldLabel() Node { - if n.Label.KeywordNode == nil { - // return nil interface to indicate absence, not a typed nil - return nil - } - return n.Label.KeywordNode -} - -func (n *GroupNode) FieldName() Node { - return n.Name -} - -func (n *GroupNode) FieldType() Node { - return n.Keyword -} - -func (n *GroupNode) FieldTag() Node { - return n.Tag -} - -func (n *GroupNode) FieldExtendee() Node { - if n.Extendee != nil { - return n.Extendee.Extendee - } - return nil -} - -func (n *GroupNode) GetGroupKeyword() Node { - return n.Keyword -} - -func (n *GroupNode) GetOptions() *CompactOptionsNode { - return n.Options -} - -func (n *GroupNode) MessageName() Node { - return n.Name -} - -// OneOfDeclNode is a node in the AST that defines a oneof. There are -// multiple types of AST nodes that declare oneofs: -// - *OneOfNode -// - *SyntheticOneOf -// -// This also allows NoSourceNode to be used in place of one of the above -// for some usages. -type OneOfDeclNode interface { - Node - OneOfName() Node -} - -// OneOfNode represents a one-of declaration. Example: -// -// oneof query { -// string by_name = 2; -// Type by_type = 3; -// Address by_address = 4; -// Labels by_label = 5; -// } -type OneOfNode struct { - compositeNode - Keyword *KeywordNode - Name *IdentNode - OpenBrace *RuneNode - Decls []OneOfElement - CloseBrace *RuneNode -} - -func (*OneOfNode) msgElement() {} - -// NewOneOfNode creates a new *OneOfNode. All arguments must be non-nil. While -// it is technically allowed for decls to be nil or empty, the resulting node -// will not be a valid oneof, which must have at least one field. -// - keyword: The token corresponding to the "oneof" keyword. -// - name: The token corresponding to the oneof's name. -// - openBrace: The token corresponding to the "{" rune that starts the body. -// - decls: All declarations inside the oneof body. -// - closeBrace: The token corresponding to the "}" rune that ends the body. -func NewOneOfNode(keyword *KeywordNode, name *IdentNode, openBrace *RuneNode, decls []OneOfElement, closeBrace *RuneNode) *OneOfNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if openBrace == nil { - panic("openBrace is nil") - } - if closeBrace == nil { - panic("closeBrace is nil") - } - children := make([]Node, 0, 4+len(decls)) - children = append(children, keyword, name, openBrace) - for _, decl := range decls { - children = append(children, decl) - } - children = append(children, closeBrace) - - for _, decl := range decls { - switch decl := decl.(type) { - case *OptionNode, *FieldNode, *GroupNode, *EmptyDeclNode: - default: - panic(fmt.Sprintf("invalid OneOfElement type: %T", decl)) - } - } - - return &OneOfNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Name: name, - OpenBrace: openBrace, - Decls: decls, - CloseBrace: closeBrace, - } -} - -func (n *OneOfNode) OneOfName() Node { - return n.Name -} - -// SyntheticOneOf is not an actual node in the AST but a synthetic node -// that implements OneOfDeclNode. These are used to represent the implicit -// oneof declarations that enclose "proto3 optional" fields. -type SyntheticOneOf struct { - Field *FieldNode -} - -// NewSyntheticOneOf creates a new *SyntheticOneOf that corresponds to the -// given proto3 optional field. -func NewSyntheticOneOf(field *FieldNode) *SyntheticOneOf { - return &SyntheticOneOf{Field: field} -} - -func (n *SyntheticOneOf) Start() *SourcePos { - return n.Field.Start() -} - -func (n *SyntheticOneOf) End() *SourcePos { - return n.Field.End() -} - -func (n *SyntheticOneOf) LeadingComments() []Comment { - return nil -} - -func (n *SyntheticOneOf) TrailingComments() []Comment { - return nil -} - -func (n *SyntheticOneOf) OneOfName() Node { - return n.Field.FieldName() -} - -// OneOfElement is an interface implemented by all AST nodes that can -// appear in the body of a oneof declaration. -type OneOfElement interface { - Node - oneOfElement() -} - -var _ OneOfElement = (*OptionNode)(nil) -var _ OneOfElement = (*FieldNode)(nil) -var _ OneOfElement = (*GroupNode)(nil) -var _ OneOfElement = (*EmptyDeclNode)(nil) - -// MapTypeNode represents the type declaration for a map field. It defines -// both the key and value types for the map. Example: -// -// map -type MapTypeNode struct { - compositeNode - Keyword *KeywordNode - OpenAngle *RuneNode - KeyType *IdentNode - Comma *RuneNode - ValueType IdentValueNode - CloseAngle *RuneNode -} - -// NewMapTypeNode creates a new *MapTypeNode. All arguments must be non-nil. -// - keyword: The token corresponding to the "map" keyword. -// - openAngle: The token corresponding to the "<" rune after the keyword. -// - keyType: The token corresponding to the key type for the map. -// - comma: The token corresponding to the "," rune between key and value types. -// - valType: The token corresponding to the value type for the map. -// - closeAngle: The token corresponding to the ">" rune that ends the declaration. -func NewMapTypeNode(keyword *KeywordNode, openAngle *RuneNode, keyType *IdentNode, comma *RuneNode, valType IdentValueNode, closeAngle *RuneNode) *MapTypeNode { - if keyword == nil { - panic("keyword is nil") - } - if openAngle == nil { - panic("openAngle is nil") - } - if keyType == nil { - panic("keyType is nil") - } - if comma == nil { - panic("comma is nil") - } - if valType == nil { - panic("valType is nil") - } - if closeAngle == nil { - panic("closeAngle is nil") - } - children := []Node{keyword, openAngle, keyType, comma, valType, closeAngle} - return &MapTypeNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - OpenAngle: openAngle, - KeyType: keyType, - Comma: comma, - ValueType: valType, - CloseAngle: closeAngle, - } -} - -// MapFieldNode represents a map field declaration. Example: -// -// map replacements = 3 [deprecated = true]; -type MapFieldNode struct { - compositeNode - MapType *MapTypeNode - Name *IdentNode - Equals *RuneNode - Tag *UintLiteralNode - Options *CompactOptionsNode - Semicolon *RuneNode -} - -func (*MapFieldNode) msgElement() {} - -// NewMapFieldNode creates a new *MapFieldNode. All arguments must be non-nil -// except opts, which may be nil. -// - mapType: The token corresponding to the map type. -// - name: The token corresponding to the field's name. -// - equals: The token corresponding to the '=' rune after the name. -// - tag: The token corresponding to the field's tag number. -// - opts: Optional set of field options. -// - semicolon: The token corresponding to the ";" rune that ends the declaration. -func NewMapFieldNode(mapType *MapTypeNode, name *IdentNode, equals *RuneNode, tag *UintLiteralNode, opts *CompactOptionsNode, semicolon *RuneNode) *MapFieldNode { - if mapType == nil { - panic("mapType is nil") - } - if name == nil { - panic("name is nil") - } - if equals == nil { - panic("equals is nil") - } - if tag == nil { - panic("tag is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - numChildren := 5 - if opts != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - children = append(children, mapType, name, equals, tag) - if opts != nil { - children = append(children, opts) - } - children = append(children, semicolon) - - return &MapFieldNode{ - compositeNode: compositeNode{ - children: children, - }, - MapType: mapType, - Name: name, - Equals: equals, - Tag: tag, - Options: opts, - Semicolon: semicolon, - } -} - -func (n *MapFieldNode) FieldLabel() Node { - return nil -} - -func (n *MapFieldNode) FieldName() Node { - return n.Name -} - -func (n *MapFieldNode) FieldType() Node { - return n.MapType -} - -func (n *MapFieldNode) FieldTag() Node { - return n.Tag -} - -func (n *MapFieldNode) FieldExtendee() Node { - return nil -} - -func (n *MapFieldNode) GetGroupKeyword() Node { - return nil -} - -func (n *MapFieldNode) GetOptions() *CompactOptionsNode { - return n.Options -} - -func (n *MapFieldNode) MessageName() Node { - return n.Name -} - -func (n *MapFieldNode) KeyField() *SyntheticMapField { - return NewSyntheticMapField(n.MapType.KeyType, 1) -} - -func (n *MapFieldNode) ValueField() *SyntheticMapField { - return NewSyntheticMapField(n.MapType.ValueType, 2) -} - -// SyntheticMapField is not an actual node in the AST but a synthetic node -// that implements FieldDeclNode. These are used to represent the implicit -// field declarations of the "key" and "value" fields in a map entry. -type SyntheticMapField struct { - Ident IdentValueNode - Tag *UintLiteralNode -} - -// NewSyntheticMapField creates a new *SyntheticMapField for the given -// identifier (either a key or value type in a map declaration) and tag -// number (1 for key, 2 for value). -func NewSyntheticMapField(ident IdentValueNode, tagNum uint64) *SyntheticMapField { - tag := &UintLiteralNode{ - terminalNode: terminalNode{ - posRange: PosRange{Start: *ident.Start(), End: *ident.End()}, - }, - Val: tagNum, - } - return &SyntheticMapField{Ident: ident, Tag: tag} -} - -func (n *SyntheticMapField) Start() *SourcePos { - return n.Ident.Start() -} - -func (n *SyntheticMapField) End() *SourcePos { - return n.Ident.End() -} - -func (n *SyntheticMapField) LeadingComments() []Comment { - return nil -} - -func (n *SyntheticMapField) TrailingComments() []Comment { - return nil -} - -func (n *SyntheticMapField) FieldLabel() Node { - return n.Ident -} - -func (n *SyntheticMapField) FieldName() Node { - return n.Ident -} - -func (n *SyntheticMapField) FieldType() Node { - return n.Ident -} - -func (n *SyntheticMapField) FieldTag() Node { - return n.Tag -} - -func (n *SyntheticMapField) FieldExtendee() Node { - return nil -} - -func (n *SyntheticMapField) GetGroupKeyword() Node { - return nil -} - -func (n *SyntheticMapField) GetOptions() *CompactOptionsNode { - return nil -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/file.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/file.go deleted file mode 100644 index 332cb0c3b..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/file.go +++ /dev/null @@ -1,236 +0,0 @@ -package ast - -import "fmt" - -// FileDeclNode is a placeholder interface for AST nodes that represent files. -// This allows NoSourceNode to be used in place of *FileNode for some usages. -type FileDeclNode interface { - Node - GetSyntax() Node -} - -var _ FileDeclNode = (*FileNode)(nil) -var _ FileDeclNode = NoSourceNode{} - -// FileNode is the root of the AST hierarchy. It represents an entire -// protobuf source file. -type FileNode struct { - compositeNode - Syntax *SyntaxNode // nil if file has no syntax declaration - Decls []FileElement - - // TODO: add Edition *EditionNode - - // Any comments that follow the last token in the file. - FinalComments []Comment - // Any whitespace at the end of the file (after the last token or - // last comment in the file). - FinalWhitespace string -} - -// NewFileNode creates a new *FileNode. The syntax parameter is optional. If it -// is absent, it means the file had no syntax declaration. -// -// This function panics if the concrete type of any element of decls is not -// from this package. -func NewFileNode(syntax *SyntaxNode, decls []FileElement) *FileNode { - numChildren := len(decls) - if syntax != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - if syntax != nil { - children = append(children, syntax) - } - for _, decl := range decls { - children = append(children, decl) - } - - for _, decl := range decls { - switch decl := decl.(type) { - case *PackageNode, *ImportNode, *OptionNode, *MessageNode, - *EnumNode, *ExtendNode, *ServiceNode, *EmptyDeclNode: - default: - panic(fmt.Sprintf("invalid FileElement type: %T", decl)) - } - } - - return &FileNode{ - compositeNode: compositeNode{ - children: children, - }, - Syntax: syntax, - Decls: decls, - } -} - -func NewEmptyFileNode(filename string) *FileNode { - return &FileNode{ - compositeNode: compositeNode{ - children: []Node{NewNoSourceNode(filename)}, - }, - } -} - -func (f *FileNode) GetSyntax() Node { - return f.Syntax -} - -// FileElement is an interface implemented by all AST nodes that are -// allowed as top-level declarations in the file. -type FileElement interface { - Node - fileElement() -} - -var _ FileElement = (*ImportNode)(nil) -var _ FileElement = (*PackageNode)(nil) -var _ FileElement = (*OptionNode)(nil) -var _ FileElement = (*MessageNode)(nil) -var _ FileElement = (*EnumNode)(nil) -var _ FileElement = (*ExtendNode)(nil) -var _ FileElement = (*ServiceNode)(nil) -var _ FileElement = (*EmptyDeclNode)(nil) - -// SyntaxNode represents a syntax declaration, which if present must be -// the first non-comment content. Example: -// -// syntax = "proto2"; -// -// Files that don't have a syntax node are assumed to use proto2 syntax. -type SyntaxNode struct { - compositeNode - Keyword *KeywordNode - Equals *RuneNode - Syntax StringValueNode - Semicolon *RuneNode -} - -// NewSyntaxNode creates a new *SyntaxNode. All four arguments must be non-nil: -// - keyword: The token corresponding to the "syntax" keyword. -// - equals: The token corresponding to the "=" rune. -// - syntax: The actual syntax value, e.g. "proto2" or "proto3". -// - semicolon: The token corresponding to the ";" rune that ends the declaration. -func NewSyntaxNode(keyword *KeywordNode, equals *RuneNode, syntax StringValueNode, semicolon *RuneNode) *SyntaxNode { - if keyword == nil { - panic("keyword is nil") - } - if equals == nil { - panic("equals is nil") - } - if syntax == nil { - panic("syntax is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - children := []Node{keyword, equals, syntax, semicolon} - return &SyntaxNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Equals: equals, - Syntax: syntax, - Semicolon: semicolon, - } -} - -// ImportNode represents an import statement. Example: -// -// import "google/protobuf/empty.proto"; -type ImportNode struct { - compositeNode - Keyword *KeywordNode - // Optional; if present indicates this is a public import - Public *KeywordNode - // Optional; if present indicates this is a weak import - Weak *KeywordNode - Name StringValueNode - Semicolon *RuneNode -} - -// NewImportNode creates a new *ImportNode. The public and weak arguments are optional -// and only one or the other (or neither) may be specified, not both. When public is -// non-nil, it indicates the "public" keyword in the import statement and means this is -// a public import. When weak is non-nil, it indicates the "weak" keyword in the import -// statement and means this is a weak import. When both are nil, this is a normal import. -// The other arguments must be non-nil: -// - keyword: The token corresponding to the "import" keyword. -// - public: The token corresponding to the optional "public" keyword. -// - weak: The token corresponding to the optional "weak" keyword. -// - name: The actual imported file name. -// - semicolon: The token corresponding to the ";" rune that ends the declaration. -func NewImportNode(keyword *KeywordNode, public *KeywordNode, weak *KeywordNode, name StringValueNode, semicolon *RuneNode) *ImportNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - numChildren := 3 - if public != nil || weak != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - children = append(children, keyword) - if public != nil { - children = append(children, public) - } else if weak != nil { - children = append(children, weak) - } - children = append(children, name, semicolon) - - return &ImportNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Public: public, - Weak: weak, - Name: name, - Semicolon: semicolon, - } -} - -func (*ImportNode) fileElement() {} - -// PackageNode represents a package declaration. Example: -// -// package foobar.com; -type PackageNode struct { - compositeNode - Keyword *KeywordNode - Name IdentValueNode - Semicolon *RuneNode -} - -func (*PackageNode) fileElement() {} - -// NewPackageNode creates a new *PackageNode. All three arguments must be non-nil: -// - keyword: The token corresponding to the "package" keyword. -// - name: The package name declared for the file. -// - semicolon: The token corresponding to the ";" rune that ends the declaration. -func NewPackageNode(keyword *KeywordNode, name IdentValueNode, semicolon *RuneNode) *PackageNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - children := []Node{keyword, name, semicolon} - return &PackageNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Name: name, - Semicolon: semicolon, - } -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/identifiers.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/identifiers.go deleted file mode 100644 index ed97e9736..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/identifiers.go +++ /dev/null @@ -1,134 +0,0 @@ -package ast - -import ( - "fmt" - "strings" -) - -// Identifier is a possibly-qualified name. This is used to distinguish -// ValueNode values that are references/identifiers vs. those that are -// string literals. -type Identifier string - -// IdentValueNode is an AST node that represents an identifier. -type IdentValueNode interface { - ValueNode - AsIdentifier() Identifier -} - -var _ IdentValueNode = (*IdentNode)(nil) -var _ IdentValueNode = (*CompoundIdentNode)(nil) - -// IdentNode represents a simple, unqualified identifier. These are used to name -// elements declared in a protobuf file or to refer to elements. Example: -// -// foobar -type IdentNode struct { - terminalNode - Val string -} - -// NewIdentNode creates a new *IdentNode. The given val is the identifier text. -func NewIdentNode(val string, info TokenInfo) *IdentNode { - return &IdentNode{ - terminalNode: info.asTerminalNode(), - Val: val, - } -} - -func (n *IdentNode) Value() interface{} { - return n.AsIdentifier() -} - -func (n *IdentNode) AsIdentifier() Identifier { - return Identifier(n.Val) -} - -// ToKeyword is used to convert identifiers to keywords. Since keywords are not -// reserved in the protobuf language, they are initially lexed as identifiers -// and then converted to keywords based on context. -func (n *IdentNode) ToKeyword() *KeywordNode { - return (*KeywordNode)(n) -} - -// CompoundIdentNode represents a qualified identifier. A qualified identifier -// has at least one dot and possibly multiple identifier names (all separated by -// dots). If the identifier has a leading dot, then it is a *fully* qualified -// identifier. Example: -// -// .com.foobar.Baz -type CompoundIdentNode struct { - compositeNode - // Optional leading dot, indicating that the identifier is fully qualified. - LeadingDot *RuneNode - Components []*IdentNode - // Dots[0] is the dot after Components[0]. The length of Dots is always - // one less than the length of Components. - Dots []*RuneNode - // The text value of the identifier, with all components and dots - // concatenated. - Val string -} - -// NewCompoundIdentNode creates a *CompoundIdentNode. The leadingDot may be nil. -// The dots arg must have a length that is one less than the length of -// components. The components arg must not be empty. -func NewCompoundIdentNode(leadingDot *RuneNode, components []*IdentNode, dots []*RuneNode) *CompoundIdentNode { - if len(components) == 0 { - panic("must have at least one component") - } - if len(dots) != len(components)-1 { - panic(fmt.Sprintf("%d components requires %d dots, not %d", len(components), len(components)-1, len(dots))) - } - numChildren := len(components)*2 - 1 - if leadingDot != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - var b strings.Builder - if leadingDot != nil { - children = append(children, leadingDot) - b.WriteRune(leadingDot.Rune) - } - for i, comp := range components { - if i > 0 { - dot := dots[i-1] - children = append(children, dot) - b.WriteRune(dot.Rune) - } - children = append(children, comp) - b.WriteString(comp.Val) - } - return &CompoundIdentNode{ - compositeNode: compositeNode{ - children: children, - }, - LeadingDot: leadingDot, - Components: components, - Dots: dots, - Val: b.String(), - } -} - -func (n *CompoundIdentNode) Value() interface{} { - return n.AsIdentifier() -} - -func (n *CompoundIdentNode) AsIdentifier() Identifier { - return Identifier(n.Val) -} - -// KeywordNode is an AST node that represents a keyword. Keywords are -// like identifiers, but they have special meaning in particular contexts. -// Example: -// -// message -type KeywordNode IdentNode - -// NewKeywordNode creates a new *KeywordNode. The given val is the keyword. -func NewKeywordNode(val string, info TokenInfo) *KeywordNode { - return &KeywordNode{ - terminalNode: info.asTerminalNode(), - Val: val, - } -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/message.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/message.go deleted file mode 100644 index c98b0f81d..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/message.go +++ /dev/null @@ -1,199 +0,0 @@ -package ast - -import "fmt" - -// MessageDeclNode is a node in the AST that defines a message type. This -// includes normal message fields as well as implicit messages: -// - *MessageNode -// - *GroupNode (the group is a field and inline message type) -// - *MapFieldNode (map fields implicitly define a MapEntry message type) -// -// This also allows NoSourceNode to be used in place of one of the above -// for some usages. -type MessageDeclNode interface { - Node - MessageName() Node -} - -var _ MessageDeclNode = (*MessageNode)(nil) -var _ MessageDeclNode = (*GroupNode)(nil) -var _ MessageDeclNode = (*MapFieldNode)(nil) -var _ MessageDeclNode = NoSourceNode{} - -// MessageNode represents a message declaration. Example: -// -// message Foo { -// string name = 1; -// repeated string labels = 2; -// bytes extra = 3; -// } -type MessageNode struct { - compositeNode - Keyword *KeywordNode - Name *IdentNode - MessageBody -} - -func (*MessageNode) fileElement() {} -func (*MessageNode) msgElement() {} - -// NewMessageNode creates a new *MessageNode. All arguments must be non-nil. -// - keyword: The token corresponding to the "message" keyword. -// - name: The token corresponding to the field's name. -// - openBrace: The token corresponding to the "{" rune that starts the body. -// - decls: All declarations inside the message body. -// - closeBrace: The token corresponding to the "}" rune that ends the body. -func NewMessageNode(keyword *KeywordNode, name *IdentNode, openBrace *RuneNode, decls []MessageElement, closeBrace *RuneNode) *MessageNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if openBrace == nil { - panic("openBrace is nil") - } - if closeBrace == nil { - panic("closeBrace is nil") - } - children := make([]Node, 0, 4+len(decls)) - children = append(children, keyword, name, openBrace) - for _, decl := range decls { - children = append(children, decl) - } - children = append(children, closeBrace) - - ret := &MessageNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Name: name, - } - populateMessageBody(&ret.MessageBody, openBrace, decls, closeBrace) - return ret -} - -func (n *MessageNode) MessageName() Node { - return n.Name -} - -// MessageBody represents the body of a message. It is used by both -// MessageNodes and GroupNodes. -type MessageBody struct { - OpenBrace *RuneNode - Decls []MessageElement - CloseBrace *RuneNode -} - -func populateMessageBody(m *MessageBody, openBrace *RuneNode, decls []MessageElement, closeBrace *RuneNode) { - m.OpenBrace = openBrace - m.Decls = decls - for _, decl := range decls { - switch decl.(type) { - case *OptionNode, *FieldNode, *MapFieldNode, *GroupNode, *OneOfNode, - *MessageNode, *EnumNode, *ExtendNode, *ExtensionRangeNode, - *ReservedNode, *EmptyDeclNode: - default: - panic(fmt.Sprintf("invalid MessageElement type: %T", decl)) - } - } - m.CloseBrace = closeBrace -} - -// MessageElement is an interface implemented by all AST nodes that can -// appear in a message body. -type MessageElement interface { - Node - msgElement() -} - -var _ MessageElement = (*OptionNode)(nil) -var _ MessageElement = (*FieldNode)(nil) -var _ MessageElement = (*MapFieldNode)(nil) -var _ MessageElement = (*OneOfNode)(nil) -var _ MessageElement = (*GroupNode)(nil) -var _ MessageElement = (*MessageNode)(nil) -var _ MessageElement = (*EnumNode)(nil) -var _ MessageElement = (*ExtendNode)(nil) -var _ MessageElement = (*ExtensionRangeNode)(nil) -var _ MessageElement = (*ReservedNode)(nil) -var _ MessageElement = (*EmptyDeclNode)(nil) - -// ExtendNode represents a declaration of extension fields. Example: -// -// extend google.protobuf.FieldOptions { -// bool redacted = 33333; -// } -type ExtendNode struct { - compositeNode - Keyword *KeywordNode - Extendee IdentValueNode - OpenBrace *RuneNode - Decls []ExtendElement - CloseBrace *RuneNode -} - -func (*ExtendNode) fileElement() {} -func (*ExtendNode) msgElement() {} - -// NewExtendNode creates a new *ExtendNode. All arguments must be non-nil. -// - keyword: The token corresponding to the "extend" keyword. -// - extendee: The token corresponding to the name of the extended message. -// - openBrace: The token corresponding to the "{" rune that starts the body. -// - decls: All declarations inside the message body. -// - closeBrace: The token corresponding to the "}" rune that ends the body. -func NewExtendNode(keyword *KeywordNode, extendee IdentValueNode, openBrace *RuneNode, decls []ExtendElement, closeBrace *RuneNode) *ExtendNode { - if keyword == nil { - panic("keyword is nil") - } - if extendee == nil { - panic("extendee is nil") - } - if openBrace == nil { - panic("openBrace is nil") - } - if closeBrace == nil { - panic("closeBrace is nil") - } - children := make([]Node, 0, 4+len(decls)) - children = append(children, keyword, extendee, openBrace) - for _, decl := range decls { - children = append(children, decl) - } - children = append(children, closeBrace) - - ret := &ExtendNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Extendee: extendee, - OpenBrace: openBrace, - Decls: decls, - CloseBrace: closeBrace, - } - for _, decl := range decls { - switch decl := decl.(type) { - case *FieldNode: - decl.Extendee = ret - case *GroupNode: - decl.Extendee = ret - case *EmptyDeclNode: - default: - panic(fmt.Sprintf("invalid ExtendElement type: %T", decl)) - } - } - return ret -} - -// ExtendElement is an interface implemented by all AST nodes that can -// appear in the body of an extends declaration. -type ExtendElement interface { - Node - extendElement() -} - -var _ ExtendElement = (*FieldNode)(nil) -var _ ExtendElement = (*GroupNode)(nil) -var _ ExtendElement = (*EmptyDeclNode)(nil) diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/no_source.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/no_source.go deleted file mode 100644 index 44e02b101..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/no_source.go +++ /dev/null @@ -1,103 +0,0 @@ -package ast - -// UnknownPos is a placeholder position when only the source file -// name is known. -func UnknownPos(filename string) *SourcePos { - return &SourcePos{Filename: filename} -} - -// NoSourceNode is a placeholder AST node that implements numerous -// interfaces in this package. It can be used to represent an AST -// element for a file whose source is not available. -type NoSourceNode struct { - pos *SourcePos -} - -// NewNoSourceNode creates a new NoSourceNode for the given filename. -func NewNoSourceNode(filename string) NoSourceNode { - return NoSourceNode{pos: UnknownPos(filename)} -} - -func (n NoSourceNode) Start() *SourcePos { - return n.pos -} - -func (n NoSourceNode) End() *SourcePos { - return n.pos -} - -func (n NoSourceNode) LeadingComments() []Comment { - return nil -} - -func (n NoSourceNode) TrailingComments() []Comment { - return nil -} - -func (n NoSourceNode) GetSyntax() Node { - return n -} - -func (n NoSourceNode) GetName() Node { - return n -} - -func (n NoSourceNode) GetValue() ValueNode { - return n -} - -func (n NoSourceNode) FieldLabel() Node { - return n -} - -func (n NoSourceNode) FieldName() Node { - return n -} - -func (n NoSourceNode) FieldType() Node { - return n -} - -func (n NoSourceNode) FieldTag() Node { - return n -} - -func (n NoSourceNode) FieldExtendee() Node { - return n -} - -func (n NoSourceNode) GetGroupKeyword() Node { - return n -} - -func (n NoSourceNode) GetOptions() *CompactOptionsNode { - return nil -} - -func (n NoSourceNode) RangeStart() Node { - return n -} - -func (n NoSourceNode) RangeEnd() Node { - return n -} - -func (n NoSourceNode) GetNumber() Node { - return n -} - -func (n NoSourceNode) MessageName() Node { - return n -} - -func (n NoSourceNode) GetInputType() Node { - return n -} - -func (n NoSourceNode) GetOutputType() Node { - return n -} - -func (n NoSourceNode) Value() interface{} { - return nil -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/node.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/node.go deleted file mode 100644 index a2a8a3b2c..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/node.go +++ /dev/null @@ -1,200 +0,0 @@ -package ast - -// Node is the interface implemented by all nodes in the AST. It -// provides information about the span of this AST node in terms -// of location in the source file. It also provides information -// about all prior comments (attached as leading comments) and -// optional subsequent comments (attached as trailing comments). -type Node interface { - Start() *SourcePos - End() *SourcePos - LeadingComments() []Comment - TrailingComments() []Comment -} - -// TerminalNode represents a leaf in the AST. These represent -// the tokens/lexemes in the protobuf language. Comments and -// whitespace are accumulated by the lexer and associated with -// the following lexed token. -type TerminalNode interface { - Node - // PopLeadingComment removes the first leading comment from this - // token and returns it. If the node has no leading comments then - // this method will panic. - PopLeadingComment() Comment - // PushTrailingComment appends the given comment to the token's - // trailing comments. - PushTrailingComment(Comment) - // LeadingWhitespace returns any whitespace between the prior comment - // (last leading comment), if any, or prior lexed token and this token. - LeadingWhitespace() string - // RawText returns the raw text of the token as read from the source. - RawText() string -} - -var _ TerminalNode = (*StringLiteralNode)(nil) -var _ TerminalNode = (*UintLiteralNode)(nil) -var _ TerminalNode = (*FloatLiteralNode)(nil) -var _ TerminalNode = (*IdentNode)(nil) -var _ TerminalNode = (*BoolLiteralNode)(nil) -var _ TerminalNode = (*SpecialFloatLiteralNode)(nil) -var _ TerminalNode = (*KeywordNode)(nil) -var _ TerminalNode = (*RuneNode)(nil) - -// TokenInfo represents state accumulated by the lexer to associated with a -// token (aka terminal node). -type TokenInfo struct { - // The location of the token in the source file. - PosRange - // The raw text of the token. - RawText string - // Any comments encountered preceding this token. - LeadingComments []Comment - // Any leading whitespace immediately preceding this token. - LeadingWhitespace string - // Any trailing comments following this token. This is usually - // empty as tokens are created by the lexer immediately and - // trailing comments are accounted for afterwards, added using - // the node's PushTrailingComment method. - TrailingComments []Comment -} - -func (t *TokenInfo) asTerminalNode() terminalNode { - return terminalNode{ - posRange: t.PosRange, - leadingComments: t.LeadingComments, - leadingWhitespace: t.LeadingWhitespace, - trailingComments: t.TrailingComments, - raw: t.RawText, - } -} - -// CompositeNode represents any non-terminal node in the tree. These -// are interior or root nodes and have child nodes. -type CompositeNode interface { - Node - // All AST nodes that are immediate children of this one. - Children() []Node -} - -// terminalNode contains book-keeping shared by all TerminalNode -// implementations. It is embedded in all such node types in this -// package. It provides the implementation of the TerminalNode -// interface. -type terminalNode struct { - posRange PosRange - leadingComments []Comment - leadingWhitespace string - trailingComments []Comment - raw string -} - -func (n *terminalNode) Start() *SourcePos { - return &n.posRange.Start -} - -func (n *terminalNode) End() *SourcePos { - return &n.posRange.End -} - -func (n *terminalNode) LeadingComments() []Comment { - return n.leadingComments -} - -func (n *terminalNode) TrailingComments() []Comment { - return n.trailingComments -} - -func (n *terminalNode) PopLeadingComment() Comment { - c := n.leadingComments[0] - n.leadingComments = n.leadingComments[1:] - return c -} - -func (n *terminalNode) PushTrailingComment(c Comment) { - n.trailingComments = append(n.trailingComments, c) -} - -func (n *terminalNode) LeadingWhitespace() string { - return n.leadingWhitespace -} - -func (n *terminalNode) RawText() string { - return n.raw -} - -// compositeNode contains book-keeping shared by all CompositeNode -// implementations. It is embedded in all such node types in this -// package. It provides the implementation of the CompositeNode -// interface. -type compositeNode struct { - children []Node -} - -func (n *compositeNode) Children() []Node { - return n.children -} - -func (n *compositeNode) Start() *SourcePos { - return n.children[0].Start() -} - -func (n *compositeNode) End() *SourcePos { - return n.children[len(n.children)-1].End() -} - -func (n *compositeNode) LeadingComments() []Comment { - return n.children[0].LeadingComments() -} - -func (n *compositeNode) TrailingComments() []Comment { - return n.children[len(n.children)-1].TrailingComments() -} - -// RuneNode represents a single rune in protobuf source. Runes -// are typically collected into tokens, but some runes stand on -// their own, such as punctuation/symbols like commas, semicolons, -// equals signs, open and close symbols (braces, brackets, angles, -// and parentheses), and periods/dots. -type RuneNode struct { - terminalNode - Rune rune -} - -// NewRuneNode creates a new *RuneNode with the given properties. -func NewRuneNode(r rune, info TokenInfo) *RuneNode { - return &RuneNode{ - terminalNode: info.asTerminalNode(), - Rune: r, - } -} - -// EmptyDeclNode represents an empty declaration in protobuf source. -// These amount to extra semicolons, with no actual content preceding -// the semicolon. -type EmptyDeclNode struct { - compositeNode - Semicolon *RuneNode -} - -// NewEmptyDeclNode creates a new *EmptyDeclNode. The one argument must -// be non-nil. -func NewEmptyDeclNode(semicolon *RuneNode) *EmptyDeclNode { - if semicolon == nil { - panic("semicolon is nil") - } - return &EmptyDeclNode{ - compositeNode: compositeNode{ - children: []Node{semicolon}, - }, - Semicolon: semicolon, - } -} - -func (e *EmptyDeclNode) fileElement() {} -func (e *EmptyDeclNode) msgElement() {} -func (e *EmptyDeclNode) extendElement() {} -func (e *EmptyDeclNode) oneOfElement() {} -func (e *EmptyDeclNode) enumElement() {} -func (e *EmptyDeclNode) serviceElement() {} -func (e *EmptyDeclNode) methodElement() {} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/options.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/options.go deleted file mode 100644 index c4ed169c4..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/options.go +++ /dev/null @@ -1,361 +0,0 @@ -package ast - -import "fmt" - -// OptionDeclNode is a placeholder interface for AST nodes that represent -// options. This allows NoSourceNode to be used in place of *OptionNode -// for some usages. -type OptionDeclNode interface { - Node - GetName() Node - GetValue() ValueNode -} - -var _ OptionDeclNode = (*OptionNode)(nil) -var _ OptionDeclNode = NoSourceNode{} - -// OptionNode represents the declaration of a single option for an element. -// It is used both for normal option declarations (start with "option" keyword -// and end with semicolon) and for compact options found in fields, enum values, -// and extension ranges. Example: -// -// option (custom.option) = "foo"; -type OptionNode struct { - compositeNode - Keyword *KeywordNode // absent for compact options - Name *OptionNameNode - Equals *RuneNode - Val ValueNode - Semicolon *RuneNode // absent for compact options -} - -func (e *OptionNode) fileElement() {} -func (e *OptionNode) msgElement() {} -func (e *OptionNode) oneOfElement() {} -func (e *OptionNode) enumElement() {} -func (e *OptionNode) serviceElement() {} -func (e *OptionNode) methodElement() {} - -// NewOptionNode creates a new *OptionNode for a full option declaration (as -// used in files, messages, oneofs, enums, services, and methods). All arguments -// must be non-nil. (Also see NewCompactOptionNode.) -// - keyword: The token corresponding to the "option" keyword. -// - name: The token corresponding to the name of the option. -// - equals: The token corresponding to the "=" rune after the name. -// - val: The token corresponding to the option value. -// - semicolon: The token corresponding to the ";" rune that ends the declaration. -func NewOptionNode(keyword *KeywordNode, name *OptionNameNode, equals *RuneNode, val ValueNode, semicolon *RuneNode) *OptionNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if equals == nil { - panic("equals is nil") - } - if val == nil { - panic("val is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - children := []Node{keyword, name, equals, val, semicolon} - return &OptionNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Name: name, - Equals: equals, - Val: val, - Semicolon: semicolon, - } -} - -// NewCompactOptionNode creates a new *OptionNode for a full compact declaration -// (as used in fields, enum values, and extension ranges). All arguments must be -// non-nil. -// - name: The token corresponding to the name of the option. -// - equals: The token corresponding to the "=" rune after the name. -// - val: The token corresponding to the option value. -func NewCompactOptionNode(name *OptionNameNode, equals *RuneNode, val ValueNode) *OptionNode { - if name == nil { - panic("name is nil") - } - if equals == nil { - panic("equals is nil") - } - if val == nil { - panic("val is nil") - } - children := []Node{name, equals, val} - return &OptionNode{ - compositeNode: compositeNode{ - children: children, - }, - Name: name, - Equals: equals, - Val: val, - } -} - -func (n *OptionNode) GetName() Node { - return n.Name -} - -func (n *OptionNode) GetValue() ValueNode { - return n.Val -} - -// OptionNameNode represents an option name or even a traversal through message -// types to name a nested option field. Example: -// -// (foo.bar).baz.(bob) -type OptionNameNode struct { - compositeNode - Parts []*FieldReferenceNode - // Dots represent the separating '.' characters between name parts. The - // length of this slice must be exactly len(Parts)-1, each item in Parts - // having a corresponding item in this slice *except the last* (since a - // trailing dot is not allowed). - // - // These do *not* include dots that are inside of an extension name. For - // example: (foo.bar).baz.(bob) has three parts: - // 1. (foo.bar) - an extension name - // 2. baz - a regular field in foo.bar - // 3. (bob) - an extension field in baz - // Note that the dot in foo.bar will thus not be present in Dots but is - // instead in Parts[0]. - Dots []*RuneNode -} - -// NewOptionNameNode creates a new *OptionNameNode. The dots arg must have a -// length that is one less than the length of parts. The parts arg must not be -// empty. -func NewOptionNameNode(parts []*FieldReferenceNode, dots []*RuneNode) *OptionNameNode { - if len(parts) == 0 { - panic("must have at least one part") - } - if len(dots) != len(parts)-1 { - panic(fmt.Sprintf("%d parts requires %d dots, not %d", len(parts), len(parts)-1, len(dots))) - } - children := make([]Node, 0, len(parts)*2-1) - for i, part := range parts { - if part == nil { - panic(fmt.Sprintf("parts[%d] is nil", i)) - } - if i > 0 { - if dots[i-1] == nil { - panic(fmt.Sprintf("dots[%d] is nil", i-1)) - } - children = append(children, dots[i-1]) - } - children = append(children, part) - } - return &OptionNameNode{ - compositeNode: compositeNode{ - children: children, - }, - Parts: parts, - Dots: dots, - } -} - -// FieldReferenceNode is a reference to a field name. It can indicate a regular -// field (simple unqualified name), an extension field (possibly-qualified name -// that is enclosed either in brackets or parentheses), or an "any" type -// reference (a type URL in the form "server.host/fully.qualified.Name" that is -// enclosed in brackets). -// -// Extension names are used in options to refer to custom options (which are -// actually extensions), in which case the name is enclosed in parentheses "(" -// and ")". They can also be used to refer to extension fields of options. -// -// Extension names are also used in message literals to set extension fields, -// in which case the name is enclosed in square brackets "[" and "]". -// -// "Any" type references can only be used in message literals, and are not -// allowed in option names. They are always enclosed in square brackets. An -// "any" type reference is distinguished from an extension name by the presence -// of a slash, which must be present in an "any" type reference and must be -// absent in an extension name. -// -// Examples: -// -// foobar -// (foo.bar) -// [foo.bar] -// [type.googleapis.com/foo.bar] -type FieldReferenceNode struct { - compositeNode - Open *RuneNode // only present for extension names and "any" type references - - // only present for "any" type references - UrlPrefix IdentValueNode - Slash *RuneNode - - Name IdentValueNode - - Close *RuneNode // only present for extension names and "any" type references -} - -// NewFieldReferenceNode creates a new *FieldReferenceNode for a regular field. -// The name arg must not be nil. -func NewFieldReferenceNode(name *IdentNode) *FieldReferenceNode { - if name == nil { - panic("name is nil") - } - children := []Node{name} - return &FieldReferenceNode{ - compositeNode: compositeNode{ - children: children, - }, - Name: name, - } -} - -// NewExtensionFieldReferenceNode creates a new *FieldReferenceNode for an -// extension field. All args must be non-nil. The openSym and closeSym runes -// should be "(" and ")" or "[" and "]". -func NewExtensionFieldReferenceNode(openSym *RuneNode, name IdentValueNode, closeSym *RuneNode) *FieldReferenceNode { - if name == nil { - panic("name is nil") - } - if openSym == nil { - panic("openSym is nil") - } - if closeSym == nil { - panic("closeSym is nil") - } - children := []Node{openSym, name, closeSym} - return &FieldReferenceNode{ - compositeNode: compositeNode{ - children: children, - }, - Open: openSym, - Name: name, - Close: closeSym, - } -} - -// NewAnyTypeReferenceNode creates a new *FieldReferenceNode for an "any" -// type reference. All args must be non-nil. The openSym and closeSym runes -// should be "[" and "]". The slashSym run should be "/". -func NewAnyTypeReferenceNode(openSym *RuneNode, urlPrefix IdentValueNode, slashSym *RuneNode, name IdentValueNode, closeSym *RuneNode) *FieldReferenceNode { - if name == nil { - panic("name is nil") - } - if openSym == nil { - panic("openSym is nil") - } - if closeSym == nil { - panic("closeSym is nil") - } - if urlPrefix == nil { - panic("urlPrefix is nil") - } - if slashSym == nil { - panic("slashSym is nil") - } - children := []Node{openSym, urlPrefix, slashSym, name, closeSym} - return &FieldReferenceNode{ - compositeNode: compositeNode{ - children: children, - }, - Open: openSym, - UrlPrefix: urlPrefix, - Slash: slashSym, - Name: name, - Close: closeSym, - } -} - -// IsExtension reports if this is an extension name or not (e.g. enclosed in -// punctuation, such as parentheses or brackets). -func (a *FieldReferenceNode) IsExtension() bool { - return a.Open != nil && a.Slash == nil -} - -// IsExtension reports if this is an extension name or not (e.g. enclosed in -// punctuation, such as parentheses or brackets). -func (a *FieldReferenceNode) IsAnyTypeReference() bool { - return a.Slash != nil -} - -func (a *FieldReferenceNode) Value() string { - if a.Open != nil { - if a.Slash != nil { - return string(a.Open.Rune) + string(a.UrlPrefix.AsIdentifier()) + string(a.Slash.Rune) + string(a.Name.AsIdentifier()) + string(a.Close.Rune) - } - return string(a.Open.Rune) + string(a.Name.AsIdentifier()) + string(a.Close.Rune) - } else { - return string(a.Name.AsIdentifier()) - } -} - -// CompactOptionsNode represents a compact options declaration, as used with -// fields, enum values, and extension ranges. Example: -// -// [deprecated = true, json_name = "foo_bar"] -type CompactOptionsNode struct { - compositeNode - OpenBracket *RuneNode - Options []*OptionNode - // Commas represent the separating ',' characters between options. The - // length of this slice must be exactly len(Options)-1, with each item - // in Options having a corresponding item in this slice *except the last* - // (since a trailing comma is not allowed). - Commas []*RuneNode - CloseBracket *RuneNode -} - -// NewCompactOptionsNode creates a *CompactOptionsNode. All args must be -// non-nil. The commas arg must have a length that is one less than the -// length of opts. The opts arg must not be empty. -func NewCompactOptionsNode(openBracket *RuneNode, opts []*OptionNode, commas []*RuneNode, closeBracket *RuneNode) *CompactOptionsNode { - if openBracket == nil { - panic("openBracket is nil") - } - if closeBracket == nil { - panic("closeBracket is nil") - } - if len(opts) == 0 { - panic("must have at least one part") - } - if len(commas) != len(opts)-1 { - panic(fmt.Sprintf("%d opts requires %d commas, not %d", len(opts), len(opts)-1, len(commas))) - } - children := make([]Node, 0, len(opts)*2+1) - children = append(children, openBracket) - for i, opt := range opts { - if i > 0 { - if commas[i-1] == nil { - panic(fmt.Sprintf("commas[%d] is nil", i-1)) - } - children = append(children, commas[i-1]) - } - if opt == nil { - panic(fmt.Sprintf("opts[%d] is nil", i)) - } - children = append(children, opt) - } - children = append(children, closeBracket) - - return &CompactOptionsNode{ - compositeNode: compositeNode{ - children: children, - }, - OpenBracket: openBracket, - Options: opts, - Commas: commas, - CloseBracket: closeBracket, - } -} - -func (e *CompactOptionsNode) GetElements() []*OptionNode { - if e == nil { - return nil - } - return e.Options -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/print.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/print.go deleted file mode 100644 index 271200c73..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/print.go +++ /dev/null @@ -1,86 +0,0 @@ -package ast - -import "io" - -// Print prints the given AST node to the given output. This operation -// basically walks the AST and, for each TerminalNode, prints the node's -// leading comments, leading whitespace, the node's raw text, and then -// any trailing comments. If the given node is a *FileNode, it will then -// also print the file's FinalComments and FinalWhitespace. -func Print(w io.Writer, node Node) error { - sw, ok := w.(stringWriter) - if !ok { - sw = &strWriter{w} - } - var err error - Walk(node, func(n Node) (bool, VisitFunc) { - if err != nil { - return false, nil - } - token, ok := n.(TerminalNode) - if !ok { - return true, nil - } - - err = printComments(sw, token.LeadingComments()) - if err != nil { - return false, nil - } - - _, err = sw.WriteString(token.LeadingWhitespace()) - if err != nil { - return false, nil - } - - _, err = sw.WriteString(token.RawText()) - if err != nil { - return false, nil - } - - err = printComments(sw, token.TrailingComments()) - return false, nil - }) - if err != nil { - return err - } - - if file, ok := node.(*FileNode); ok { - err = printComments(sw, file.FinalComments) - if err != nil { - return err - } - _, err = sw.WriteString(file.FinalWhitespace) - return err - } - - return nil -} - -func printComments(sw stringWriter, comments []Comment) error { - for _, comment := range comments { - if _, err := sw.WriteString(comment.LeadingWhitespace); err != nil { - return err - } - if _, err := sw.WriteString(comment.Text); err != nil { - return err - } - } - return nil -} - -// many io.Writer impls also provide a string-based method -type stringWriter interface { - WriteString(s string) (n int, err error) -} - -// adapter, in case the given writer does NOT provide a string-based method -type strWriter struct { - io.Writer -} - -func (s *strWriter) WriteString(str string) (int, error) { - if str == "" { - return 0, nil - } - return s.Write([]byte(str)) -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/ranges.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/ranges.go deleted file mode 100644 index cdd78baf9..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/ranges.go +++ /dev/null @@ -1,305 +0,0 @@ -package ast - -import "fmt" - -// ExtensionRangeNode represents an extension range declaration in an extendable -// message. Example: -// -// extensions 100 to max; -type ExtensionRangeNode struct { - compositeNode - Keyword *KeywordNode - Ranges []*RangeNode - // Commas represent the separating ',' characters between ranges. The - // length of this slice must be exactly len(Ranges)-1, each item in Ranges - // having a corresponding item in this slice *except the last* (since a - // trailing comma is not allowed). - Commas []*RuneNode - Options *CompactOptionsNode - Semicolon *RuneNode -} - -func (e *ExtensionRangeNode) msgElement() {} - -// NewExtensionRangeNode creates a new *ExtensionRangeNode. All args must be -// non-nil except opts, which may be nil. -// - keyword: The token corresponding to the "extends" keyword. -// - ranges: One or more range expressions. -// - commas: Tokens that represent the "," runes that delimit the range expressions. -// The length of commas must be one less than the length of ranges. -// - opts: The node corresponding to options that apply to each of the ranges. -// - semicolon The token corresponding to the ";" rune that ends the declaration. -func NewExtensionRangeNode(keyword *KeywordNode, ranges []*RangeNode, commas []*RuneNode, opts *CompactOptionsNode, semicolon *RuneNode) *ExtensionRangeNode { - if keyword == nil { - panic("keyword is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - if len(ranges) == 0 { - panic("must have at least one range") - } - if len(commas) != len(ranges)-1 { - panic(fmt.Sprintf("%d ranges requires %d commas, not %d", len(ranges), len(ranges)-1, len(commas))) - } - numChildren := len(ranges)*2 + 1 - if opts != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - children = append(children, keyword) - for i, rng := range ranges { - if i > 0 { - if commas[i-1] == nil { - panic(fmt.Sprintf("commas[%d] is nil", i-1)) - } - children = append(children, commas[i-1]) - } - if rng == nil { - panic(fmt.Sprintf("ranges[%d] is nil", i)) - } - children = append(children, rng) - } - if opts != nil { - children = append(children, opts) - } - children = append(children, semicolon) - return &ExtensionRangeNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Ranges: ranges, - Commas: commas, - Options: opts, - Semicolon: semicolon, - } -} - -// RangeDeclNode is a placeholder interface for AST nodes that represent -// numeric values. This allows NoSourceNode to be used in place of *RangeNode -// for some usages. -type RangeDeclNode interface { - Node - RangeStart() Node - RangeEnd() Node -} - -var _ RangeDeclNode = (*RangeNode)(nil) -var _ RangeDeclNode = NoSourceNode{} - -// RangeNode represents a range expression, used in both extension ranges and -// reserved ranges. Example: -// -// 1000 to max -type RangeNode struct { - compositeNode - StartVal IntValueNode - // if To is non-nil, then exactly one of EndVal or Max must also be non-nil - To *KeywordNode - // EndVal and Max are mutually exclusive - EndVal IntValueNode - Max *KeywordNode -} - -// NewRangeNode creates a new *RangeNode. The start argument must be non-nil. -// The to argument represents the "to" keyword. If present (i.e. if it is non-nil), -// then so must be exactly one of end or max. If max is non-nil, it indicates a -// "100 to max" style range. But if end is non-nil, the end of the range is a -// literal, such as "100 to 200". -func NewRangeNode(start IntValueNode, to *KeywordNode, end IntValueNode, max *KeywordNode) *RangeNode { - if start == nil { - panic("start is nil") - } - numChildren := 1 - if to != nil { - if end == nil && max == nil { - panic("to is not nil, but end and max both are") - } - if end != nil && max != nil { - panic("end and max cannot be both non-nil") - } - numChildren = 3 - } else { - if end != nil { - panic("to is nil, but end is not") - } - if max != nil { - panic("to is nil, but max is not") - } - } - children := make([]Node, 0, numChildren) - children = append(children, start) - if to != nil { - children = append(children, to) - if end != nil { - children = append(children, end) - } else { - children = append(children, max) - } - } - return &RangeNode{ - compositeNode: compositeNode{ - children: children, - }, - StartVal: start, - To: to, - EndVal: end, - Max: max, - } -} - -func (n *RangeNode) RangeStart() Node { - return n.StartVal -} - -func (n *RangeNode) RangeEnd() Node { - if n.Max != nil { - return n.Max - } - if n.EndVal != nil { - return n.EndVal - } - return n.StartVal -} - -func (n *RangeNode) StartValue() interface{} { - return n.StartVal.Value() -} - -func (n *RangeNode) StartValueAsInt32(min, max int32) (int32, bool) { - return AsInt32(n.StartVal, min, max) -} - -func (n *RangeNode) EndValue() interface{} { - if n.EndVal == nil { - return nil - } - return n.EndVal.Value() -} - -func (n *RangeNode) EndValueAsInt32(min, max int32) (int32, bool) { - if n.Max != nil { - return max, true - } - if n.EndVal == nil { - return n.StartValueAsInt32(min, max) - } - return AsInt32(n.EndVal, min, max) -} - -// ReservedNode represents reserved declaration, which can be used to reserve -// either names or numbers. Examples: -// -// reserved 1, 10-12, 15; -// reserved "foo", "bar", "baz"; -type ReservedNode struct { - compositeNode - Keyword *KeywordNode - // If non-empty, this node represents reserved ranges and Names will be empty. - Ranges []*RangeNode - // If non-empty, this node represents reserved names and Ranges will be empty. - Names []StringValueNode - // Commas represent the separating ',' characters between options. The - // length of this slice must be exactly len(Ranges)-1 or len(Names)-1, depending - // on whether this node represents reserved ranges or reserved names. Each item - // in Ranges or Names has a corresponding item in this slice *except the last* - // (since a trailing comma is not allowed). - Commas []*RuneNode - Semicolon *RuneNode -} - -func (*ReservedNode) msgElement() {} -func (*ReservedNode) enumElement() {} - -// NewReservedRangesNode creates a new *ReservedNode that represents reserved -// numeric ranges. All args must be non-nil. -// - keyword: The token corresponding to the "reserved" keyword. -// - ranges: One or more range expressions. -// - commas: Tokens that represent the "," runes that delimit the range expressions. -// The length of commas must be one less than the length of ranges. -// - semicolon The token corresponding to the ";" rune that ends the declaration. -func NewReservedRangesNode(keyword *KeywordNode, ranges []*RangeNode, commas []*RuneNode, semicolon *RuneNode) *ReservedNode { - if keyword == nil { - panic("keyword is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - if len(ranges) == 0 { - panic("must have at least one range") - } - if len(commas) != len(ranges)-1 { - panic(fmt.Sprintf("%d ranges requires %d commas, not %d", len(ranges), len(ranges)-1, len(commas))) - } - children := make([]Node, 0, len(ranges)*2+1) - children = append(children, keyword) - for i, rng := range ranges { - if i > 0 { - if commas[i-1] == nil { - panic(fmt.Sprintf("commas[%d] is nil", i-1)) - } - children = append(children, commas[i-1]) - } - if rng == nil { - panic(fmt.Sprintf("ranges[%d] is nil", i)) - } - children = append(children, rng) - } - children = append(children, semicolon) - return &ReservedNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Ranges: ranges, - Commas: commas, - Semicolon: semicolon, - } -} - -// NewReservedNamesNode creates a new *ReservedNode that represents reserved -// names. All args must be non-nil. -// - keyword: The token corresponding to the "reserved" keyword. -// - names: One or more names. -// - commas: Tokens that represent the "," runes that delimit the names. -// The length of commas must be one less than the length of names. -// - semicolon The token corresponding to the ";" rune that ends the declaration. -func NewReservedNamesNode(keyword *KeywordNode, names []StringValueNode, commas []*RuneNode, semicolon *RuneNode) *ReservedNode { - if keyword == nil { - panic("keyword is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - if len(names) == 0 { - panic("must have at least one name") - } - if len(commas) != len(names)-1 { - panic(fmt.Sprintf("%d names requires %d commas, not %d", len(names), len(names)-1, len(commas))) - } - children := make([]Node, 0, len(names)*2+1) - children = append(children, keyword) - for i, name := range names { - if i > 0 { - if commas[i-1] == nil { - panic(fmt.Sprintf("commas[%d] is nil", i-1)) - } - children = append(children, commas[i-1]) - } - if name == nil { - panic(fmt.Sprintf("names[%d] is nil", i)) - } - children = append(children, name) - } - children = append(children, semicolon) - return &ReservedNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Names: names, - Commas: commas, - Semicolon: semicolon, - } -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/service.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/service.go deleted file mode 100644 index 739b29cc1..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/service.go +++ /dev/null @@ -1,273 +0,0 @@ -package ast - -import "fmt" - -// ServiceNode represents a service declaration. Example: -// -// service Foo { -// rpc Bar (Baz) returns (Bob); -// rpc Frobnitz (stream Parts) returns (Gyzmeaux); -// } -type ServiceNode struct { - compositeNode - Keyword *KeywordNode - Name *IdentNode - OpenBrace *RuneNode - Decls []ServiceElement - CloseBrace *RuneNode -} - -func (*ServiceNode) fileElement() {} - -// NewServiceNode creates a new *ServiceNode. All arguments must be non-nil. -// - keyword: The token corresponding to the "service" keyword. -// - name: The token corresponding to the service's name. -// - openBrace: The token corresponding to the "{" rune that starts the body. -// - decls: All declarations inside the service body. -// - closeBrace: The token corresponding to the "}" rune that ends the body. -func NewServiceNode(keyword *KeywordNode, name *IdentNode, openBrace *RuneNode, decls []ServiceElement, closeBrace *RuneNode) *ServiceNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if openBrace == nil { - panic("openBrace is nil") - } - if closeBrace == nil { - panic("closeBrace is nil") - } - children := make([]Node, 0, 4+len(decls)) - children = append(children, keyword, name, openBrace) - for _, decl := range decls { - children = append(children, decl) - } - children = append(children, closeBrace) - - for _, decl := range decls { - switch decl := decl.(type) { - case *OptionNode, *RPCNode, *EmptyDeclNode: - default: - panic(fmt.Sprintf("invalid ServiceElement type: %T", decl)) - } - } - - return &ServiceNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Name: name, - OpenBrace: openBrace, - Decls: decls, - CloseBrace: closeBrace, - } -} - -// ServiceElement is an interface implemented by all AST nodes that can -// appear in the body of a service declaration. -type ServiceElement interface { - Node - serviceElement() -} - -var _ ServiceElement = (*OptionNode)(nil) -var _ ServiceElement = (*RPCNode)(nil) -var _ ServiceElement = (*EmptyDeclNode)(nil) - -// RPCDeclNode is a placeholder interface for AST nodes that represent RPC -// declarations. This allows NoSourceNode to be used in place of *RPCNode -// for some usages. -type RPCDeclNode interface { - Node - GetInputType() Node - GetOutputType() Node -} - -var _ RPCDeclNode = (*RPCNode)(nil) -var _ RPCDeclNode = NoSourceNode{} - -// RPCNode represents an RPC declaration. Example: -// -// rpc Foo (Bar) returns (Baz); -type RPCNode struct { - compositeNode - Keyword *KeywordNode - Name *IdentNode - Input *RPCTypeNode - Returns *KeywordNode - Output *RPCTypeNode - Semicolon *RuneNode - OpenBrace *RuneNode - Decls []RPCElement - CloseBrace *RuneNode -} - -func (n *RPCNode) serviceElement() {} - -// NewRPCNode creates a new *RPCNode with no body. All arguments must be non-nil. -// - keyword: The token corresponding to the "rpc" keyword. -// - name: The token corresponding to the RPC's name. -// - input: The token corresponding to the RPC input message type. -// - returns: The token corresponding to the "returns" keyword that precedes the output type. -// - output: The token corresponding to the RPC output message type. -// - semicolon: The token corresponding to the ";" rune that ends the declaration. -func NewRPCNode(keyword *KeywordNode, name *IdentNode, input *RPCTypeNode, returns *KeywordNode, output *RPCTypeNode, semicolon *RuneNode) *RPCNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if input == nil { - panic("input is nil") - } - if returns == nil { - panic("returns is nil") - } - if output == nil { - panic("output is nil") - } - if semicolon == nil { - panic("semicolon is nil") - } - children := []Node{keyword, name, input, returns, output, semicolon} - return &RPCNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Name: name, - Input: input, - Returns: returns, - Output: output, - Semicolon: semicolon, - } -} - -// NewRPCNodeWithBody creates a new *RPCNode that includes a body (and possibly -// options). All arguments must be non-nil. -// - keyword: The token corresponding to the "rpc" keyword. -// - name: The token corresponding to the RPC's name. -// - input: The token corresponding to the RPC input message type. -// - returns: The token corresponding to the "returns" keyword that precedes the output type. -// - output: The token corresponding to the RPC output message type. -// - openBrace: The token corresponding to the "{" rune that starts the body. -// - decls: All declarations inside the RPC body. -// - closeBrace: The token corresponding to the "}" rune that ends the body. -func NewRPCNodeWithBody(keyword *KeywordNode, name *IdentNode, input *RPCTypeNode, returns *KeywordNode, output *RPCTypeNode, openBrace *RuneNode, decls []RPCElement, closeBrace *RuneNode) *RPCNode { - if keyword == nil { - panic("keyword is nil") - } - if name == nil { - panic("name is nil") - } - if input == nil { - panic("input is nil") - } - if returns == nil { - panic("returns is nil") - } - if output == nil { - panic("output is nil") - } - if openBrace == nil { - panic("openBrace is nil") - } - if closeBrace == nil { - panic("closeBrace is nil") - } - children := make([]Node, 0, 7+len(decls)) - children = append(children, keyword, name, input, returns, output, openBrace) - for _, decl := range decls { - children = append(children, decl) - } - children = append(children, closeBrace) - - for _, decl := range decls { - switch decl := decl.(type) { - case *OptionNode, *EmptyDeclNode: - default: - panic(fmt.Sprintf("invalid RPCElement type: %T", decl)) - } - } - - return &RPCNode{ - compositeNode: compositeNode{ - children: children, - }, - Keyword: keyword, - Name: name, - Input: input, - Returns: returns, - Output: output, - OpenBrace: openBrace, - Decls: decls, - CloseBrace: closeBrace, - } -} - -func (n *RPCNode) GetInputType() Node { - return n.Input.MessageType -} - -func (n *RPCNode) GetOutputType() Node { - return n.Output.MessageType -} - -// RPCElement is an interface implemented by all AST nodes that can -// appear in the body of an rpc declaration (aka method). -type RPCElement interface { - Node - methodElement() -} - -var _ RPCElement = (*OptionNode)(nil) -var _ RPCElement = (*EmptyDeclNode)(nil) - -// RPCTypeNode represents the declaration of a request or response type for an -// RPC. Example: -// -// (stream foo.Bar) -type RPCTypeNode struct { - compositeNode - OpenParen *RuneNode - Stream *KeywordNode - MessageType IdentValueNode - CloseParen *RuneNode -} - -// NewRPCTypeNode creates a new *RPCTypeNode. All arguments must be non-nil -// except stream, which may be nil. -// - openParen: The token corresponding to the "(" rune that starts the declaration. -// - stream: The token corresponding to the "stream" keyword or nil if not present. -// - msgType: The token corresponding to the message type's name. -// - closeParen: The token corresponding to the ")" rune that ends the declaration. -func NewRPCTypeNode(openParen *RuneNode, stream *KeywordNode, msgType IdentValueNode, closeParen *RuneNode) *RPCTypeNode { - if openParen == nil { - panic("openParen is nil") - } - if msgType == nil { - panic("msgType is nil") - } - if closeParen == nil { - panic("closeParen is nil") - } - var children []Node - if stream != nil { - children = []Node{openParen, stream, msgType, closeParen} - } else { - children = []Node{openParen, msgType, closeParen} - } - - return &RPCTypeNode{ - compositeNode: compositeNode{ - children: children, - }, - OpenParen: openParen, - Stream: stream, - MessageType: msgType, - CloseParen: closeParen, - } -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/source_pos.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/source_pos.go deleted file mode 100644 index 8ab09c6f2..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/source_pos.go +++ /dev/null @@ -1,29 +0,0 @@ -package ast - -import ( - "github.com/bufbuild/protocompile/ast" -) - -// SourcePos identifies a location in a proto source file. -type SourcePos = ast.SourcePos - -// PosRange is a range of positions in a source file that indicates -// the span of some region of source, such as a single token or -// a sub-tree of the AST. -type PosRange struct { - Start, End SourcePos -} - -// Comment represents a single comment in a source file. It indicates -// the position of the comment and its contents. -type Comment struct { - // The location of the comment in the source file. - PosRange - // Any whitespace between the prior lexical element (either a token - // or other comment) and this comment. - LeadingWhitespace string - // The text of the comment, including any "//" or "/*" and "*/" - // symbols at the start and end. Single-line comments will include - // the trailing newline rune in Text. - Text string -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/values.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/values.go deleted file mode 100644 index 91f5a3545..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/values.go +++ /dev/null @@ -1,575 +0,0 @@ -package ast - -import ( - "fmt" - "math" - "strings" -) - -// ValueNode is an AST node that represents a literal value. -// -// It also includes references (e.g. IdentifierValueNode), which can be -// used as values in some contexts, such as describing the default value -// for a field, which can refer to an enum value. -// -// This also allows NoSourceNode to be used in place of a real value node -// for some usages. -type ValueNode interface { - Node - // Value returns a Go representation of the value. For scalars, this - // will be a string, int64, uint64, float64, or bool. This could also - // be an Identifier (e.g. IdentValueNodes). It can also be a composite - // literal: - // * For array literals, the type returned will be []ValueNode - // * For message literals, the type returned will be []*MessageFieldNode - Value() interface{} -} - -var _ ValueNode = (*IdentNode)(nil) -var _ ValueNode = (*CompoundIdentNode)(nil) -var _ ValueNode = (*StringLiteralNode)(nil) -var _ ValueNode = (*CompoundStringLiteralNode)(nil) -var _ ValueNode = (*UintLiteralNode)(nil) -var _ ValueNode = (*PositiveUintLiteralNode)(nil) -var _ ValueNode = (*NegativeIntLiteralNode)(nil) -var _ ValueNode = (*FloatLiteralNode)(nil) -var _ ValueNode = (*SpecialFloatLiteralNode)(nil) -var _ ValueNode = (*SignedFloatLiteralNode)(nil) -var _ ValueNode = (*BoolLiteralNode)(nil) -var _ ValueNode = (*ArrayLiteralNode)(nil) -var _ ValueNode = (*MessageLiteralNode)(nil) -var _ ValueNode = NoSourceNode{} - -// StringValueNode is an AST node that represents a string literal. -// Such a node can be a single literal (*StringLiteralNode) or a -// concatenation of multiple literals (*CompoundStringLiteralNode). -type StringValueNode interface { - ValueNode - AsString() string -} - -var _ StringValueNode = (*StringLiteralNode)(nil) -var _ StringValueNode = (*CompoundStringLiteralNode)(nil) - -// StringLiteralNode represents a simple string literal. Example: -// -// "proto2" -type StringLiteralNode struct { - terminalNode - // Val is the actual string value that the literal indicates. - Val string -} - -// NewStringLiteralNode creates a new *StringLiteralNode with the given val. -func NewStringLiteralNode(val string, info TokenInfo) *StringLiteralNode { - return &StringLiteralNode{ - terminalNode: info.asTerminalNode(), - Val: val, - } -} - -func (n *StringLiteralNode) Value() interface{} { - return n.AsString() -} - -func (n *StringLiteralNode) AsString() string { - return n.Val -} - -// CompoundStringLiteralNode represents a compound string literal, which is -// the concatenaton of adjacent string literals. Example: -// -// "this " "is" " all one " "string" -type CompoundStringLiteralNode struct { - compositeNode - Val string -} - -// NewCompoundLiteralStringNode creates a new *CompoundStringLiteralNode that -// consists of the given string components. The components argument may not be -// empty. -func NewCompoundLiteralStringNode(components ...*StringLiteralNode) *CompoundStringLiteralNode { - if len(components) == 0 { - panic("must have at least one component") - } - children := make([]Node, len(components)) - var b strings.Builder - for i, comp := range components { - children[i] = comp - b.WriteString(comp.Val) - } - return &CompoundStringLiteralNode{ - compositeNode: compositeNode{ - children: children, - }, - Val: b.String(), - } -} - -func (n *CompoundStringLiteralNode) Value() interface{} { - return n.AsString() -} - -func (n *CompoundStringLiteralNode) AsString() string { - return n.Val -} - -// IntValueNode is an AST node that represents an integer literal. If -// an integer literal is too large for an int64 (or uint64 for -// positive literals), it is represented instead by a FloatValueNode. -type IntValueNode interface { - ValueNode - AsInt64() (int64, bool) - AsUint64() (uint64, bool) -} - -// AsInt32 range checks the given int value and returns its value is -// in the range or 0, false if it is outside the range. -func AsInt32(n IntValueNode, min, max int32) (int32, bool) { - i, ok := n.AsInt64() - if !ok { - return 0, false - } - if i < int64(min) || i > int64(max) { - return 0, false - } - return int32(i), true -} - -var _ IntValueNode = (*UintLiteralNode)(nil) -var _ IntValueNode = (*PositiveUintLiteralNode)(nil) -var _ IntValueNode = (*NegativeIntLiteralNode)(nil) - -// UintLiteralNode represents a simple integer literal with no sign character. -type UintLiteralNode struct { - terminalNode - // Val is the numeric value indicated by the literal - Val uint64 -} - -// NewUintLiteralNode creates a new *UintLiteralNode with the given val. -func NewUintLiteralNode(val uint64, info TokenInfo) *UintLiteralNode { - return &UintLiteralNode{ - terminalNode: info.asTerminalNode(), - Val: val, - } -} - -func (n *UintLiteralNode) Value() interface{} { - return n.Val -} - -func (n *UintLiteralNode) AsInt64() (int64, bool) { - if n.Val > math.MaxInt64 { - return 0, false - } - return int64(n.Val), true -} - -func (n *UintLiteralNode) AsUint64() (uint64, bool) { - return n.Val, true -} - -func (n *UintLiteralNode) AsFloat() float64 { - return float64(n.Val) -} - -// PositiveUintLiteralNode represents an integer literal with a positive (+) sign. -// -// Deprecated: A valid AST will not contain a node of this type. The Protobuf -// language does not actually allow a numeric literal to have a leading "+" -// positive sign. -type PositiveUintLiteralNode struct { - compositeNode - Plus *RuneNode - Uint *UintLiteralNode - Val uint64 -} - -// NewPositiveUintLiteralNode creates a new *PositiveUintLiteralNode. Both -// arguments must be non-nil. -// -// Deprecated: The ast.PositiveUintLiteralNode node type should not be used. -func NewPositiveUintLiteralNode(sign *RuneNode, i *UintLiteralNode) *PositiveUintLiteralNode { - if sign == nil { - panic("sign is nil") - } - if i == nil { - panic("i is nil") - } - children := []Node{sign, i} - return &PositiveUintLiteralNode{ - compositeNode: compositeNode{ - children: children, - }, - Plus: sign, - Uint: i, - Val: i.Val, - } -} - -func (n *PositiveUintLiteralNode) Value() interface{} { - return n.Val -} - -func (n *PositiveUintLiteralNode) AsInt64() (int64, bool) { - if n.Val > math.MaxInt64 { - return 0, false - } - return int64(n.Val), true -} - -func (n *PositiveUintLiteralNode) AsUint64() (uint64, bool) { - return n.Val, true -} - -// NegativeIntLiteralNode represents an integer literal with a negative (-) sign. -type NegativeIntLiteralNode struct { - compositeNode - Minus *RuneNode - Uint *UintLiteralNode - Val int64 -} - -// NewNegativeIntLiteralNode creates a new *NegativeIntLiteralNode. Both -// arguments must be non-nil. -func NewNegativeIntLiteralNode(sign *RuneNode, i *UintLiteralNode) *NegativeIntLiteralNode { - if sign == nil { - panic("sign is nil") - } - if i == nil { - panic("i is nil") - } - children := []Node{sign, i} - return &NegativeIntLiteralNode{ - compositeNode: compositeNode{ - children: children, - }, - Minus: sign, - Uint: i, - Val: -int64(i.Val), - } -} - -func (n *NegativeIntLiteralNode) Value() interface{} { - return n.Val -} - -func (n *NegativeIntLiteralNode) AsInt64() (int64, bool) { - return n.Val, true -} - -func (n *NegativeIntLiteralNode) AsUint64() (uint64, bool) { - if n.Val < 0 { - return 0, false - } - return uint64(n.Val), true -} - -// FloatValueNode is an AST node that represents a numeric literal with -// a floating point, in scientific notation, or too large to fit in an -// int64 or uint64. -type FloatValueNode interface { - ValueNode - AsFloat() float64 -} - -var _ FloatValueNode = (*FloatLiteralNode)(nil) -var _ FloatValueNode = (*SpecialFloatLiteralNode)(nil) -var _ FloatValueNode = (*UintLiteralNode)(nil) - -// FloatLiteralNode represents a floating point numeric literal. -type FloatLiteralNode struct { - terminalNode - // Val is the numeric value indicated by the literal - Val float64 -} - -// NewFloatLiteralNode creates a new *FloatLiteralNode with the given val. -func NewFloatLiteralNode(val float64, info TokenInfo) *FloatLiteralNode { - return &FloatLiteralNode{ - terminalNode: info.asTerminalNode(), - Val: val, - } -} - -func (n *FloatLiteralNode) Value() interface{} { - return n.AsFloat() -} - -func (n *FloatLiteralNode) AsFloat() float64 { - return n.Val -} - -// SpecialFloatLiteralNode represents a special floating point numeric literal -// for "inf" and "nan" values. -type SpecialFloatLiteralNode struct { - *KeywordNode - Val float64 -} - -// NewSpecialFloatLiteralNode returns a new *SpecialFloatLiteralNode for the -// given keyword, which must be "inf" or "nan". -func NewSpecialFloatLiteralNode(name *KeywordNode) *SpecialFloatLiteralNode { - var f float64 - if name.Val == "inf" { - f = math.Inf(1) - } else { - f = math.NaN() - } - return &SpecialFloatLiteralNode{ - KeywordNode: name, - Val: f, - } -} - -func (n *SpecialFloatLiteralNode) Value() interface{} { - return n.AsFloat() -} - -func (n *SpecialFloatLiteralNode) AsFloat() float64 { - return n.Val -} - -// SignedFloatLiteralNode represents a signed floating point number. -type SignedFloatLiteralNode struct { - compositeNode - Sign *RuneNode - Float FloatValueNode - Val float64 -} - -// NewSignedFloatLiteralNode creates a new *SignedFloatLiteralNode. Both -// arguments must be non-nil. -func NewSignedFloatLiteralNode(sign *RuneNode, f FloatValueNode) *SignedFloatLiteralNode { - if sign == nil { - panic("sign is nil") - } - if f == nil { - panic("f is nil") - } - children := []Node{sign, f} - val := f.AsFloat() - if sign.Rune == '-' { - val = -val - } - return &SignedFloatLiteralNode{ - compositeNode: compositeNode{ - children: children, - }, - Sign: sign, - Float: f, - Val: val, - } -} - -func (n *SignedFloatLiteralNode) Value() interface{} { - return n.Val -} - -func (n *SignedFloatLiteralNode) AsFloat() float64 { - return n.Val -} - -// BoolLiteralNode represents a boolean literal. -// -// Deprecated: The AST uses IdentNode for boolean literals, where the -// identifier value is "true" or "false". This is required because an -// identifier "true" is not necessarily a boolean value as it could also -// be an enum value named "true" (ditto for "false"). -type BoolLiteralNode struct { - *KeywordNode - Val bool -} - -// NewBoolLiteralNode returns a new *BoolLiteralNode for the given keyword, -// which must be "true" or "false". -func NewBoolLiteralNode(name *KeywordNode) *BoolLiteralNode { - return &BoolLiteralNode{ - KeywordNode: name, - Val: name.Val == "true", - } -} - -func (n *BoolLiteralNode) Value() interface{} { - return n.Val -} - -// ArrayLiteralNode represents an array literal, which is only allowed inside of -// a MessageLiteralNode, to indicate values for a repeated field. Example: -// -// ["foo", "bar", "baz"] -type ArrayLiteralNode struct { - compositeNode - OpenBracket *RuneNode - Elements []ValueNode - // Commas represent the separating ',' characters between elements. The - // length of this slice must be exactly len(Elements)-1, with each item - // in Elements having a corresponding item in this slice *except the last* - // (since a trailing comma is not allowed). - Commas []*RuneNode - CloseBracket *RuneNode -} - -// NewArrayLiteralNode creates a new *ArrayLiteralNode. The openBracket and -// closeBracket args must be non-nil and represent the "[" and "]" runes that -// surround the array values. The given commas arg must have a length that is -// one less than the length of the vals arg. However, vals may be empty, in -// which case commas must also be empty. -func NewArrayLiteralNode(openBracket *RuneNode, vals []ValueNode, commas []*RuneNode, closeBracket *RuneNode) *ArrayLiteralNode { - if openBracket == nil { - panic("openBracket is nil") - } - if closeBracket == nil { - panic("closeBracket is nil") - } - if len(vals) == 0 && len(commas) != 0 { - panic("vals is empty but commas is not") - } - if len(vals) > 0 && len(commas) != len(vals)-1 { - panic(fmt.Sprintf("%d vals requires %d commas, not %d", len(vals), len(vals)-1, len(commas))) - } - children := make([]Node, 0, len(vals)*2+1) - children = append(children, openBracket) - for i, val := range vals { - if i > 0 { - if commas[i-1] == nil { - panic(fmt.Sprintf("commas[%d] is nil", i-1)) - } - children = append(children, commas[i-1]) - } - if val == nil { - panic(fmt.Sprintf("vals[%d] is nil", i)) - } - children = append(children, val) - } - children = append(children, closeBracket) - - return &ArrayLiteralNode{ - compositeNode: compositeNode{ - children: children, - }, - OpenBracket: openBracket, - Elements: vals, - Commas: commas, - CloseBracket: closeBracket, - } -} - -func (n *ArrayLiteralNode) Value() interface{} { - return n.Elements -} - -// MessageLiteralNode represents a message literal, which is compatible with the -// protobuf text format and can be used for custom options with message types. -// Example: -// -// { foo:1 foo:2 foo:3 bar: } -type MessageLiteralNode struct { - compositeNode - Open *RuneNode // should be '{' or '<' - Elements []*MessageFieldNode - // Separator characters between elements, which can be either ',' - // or ';' if present. This slice must be exactly len(Elements) in - // length, with each item in Elements having one corresponding item - // in Seps. Separators in message literals are optional, so a given - // item in this slice may be nil to indicate absence of a separator. - Seps []*RuneNode - Close *RuneNode // should be '}' or '>', depending on Open -} - -// NewMessageLiteralNode creates a new *MessageLiteralNode. The openSym and -// closeSym runes must not be nil and should be "{" and "}" or "<" and ">". -// -// Unlike separators (dots and commas) used for other AST nodes that represent -// a list of elements, the seps arg must be the SAME length as vals, and it may -// contain nil values to indicate absence of a separator (in fact, it could be -// all nils). -func NewMessageLiteralNode(openSym *RuneNode, vals []*MessageFieldNode, seps []*RuneNode, closeSym *RuneNode) *MessageLiteralNode { - if openSym == nil { - panic("openSym is nil") - } - if closeSym == nil { - panic("closeSym is nil") - } - if len(seps) != len(vals) { - panic(fmt.Sprintf("%d vals requires %d commas, not %d", len(vals), len(vals), len(seps))) - } - numChildren := len(vals) + 2 - for _, sep := range seps { - if sep != nil { - numChildren++ - } - } - children := make([]Node, 0, numChildren) - children = append(children, openSym) - for i, val := range vals { - if val == nil { - panic(fmt.Sprintf("vals[%d] is nil", i)) - } - children = append(children, val) - if seps[i] != nil { - children = append(children, seps[i]) - } - } - children = append(children, closeSym) - - return &MessageLiteralNode{ - compositeNode: compositeNode{ - children: children, - }, - Open: openSym, - Elements: vals, - Seps: seps, - Close: closeSym, - } -} - -func (n *MessageLiteralNode) Value() interface{} { - return n.Elements -} - -// MessageFieldNode represents a single field (name and value) inside of a -// message literal. Example: -// -// foo:"bar" -type MessageFieldNode struct { - compositeNode - Name *FieldReferenceNode - // Sep represents the ':' separator between the name and value. If - // the value is a message literal (and thus starts with '<' or '{') - // or an array literal (starting with '[') then the separator is - // optional, and thus may be nil. - Sep *RuneNode - Val ValueNode -} - -// NewMessageFieldNode creates a new *MessageFieldNode. All args except sep -// must be non-nil. -func NewMessageFieldNode(name *FieldReferenceNode, sep *RuneNode, val ValueNode) *MessageFieldNode { - if name == nil { - panic("name is nil") - } - if val == nil { - panic("val is nil") - } - numChildren := 2 - if sep != nil { - numChildren++ - } - children := make([]Node, 0, numChildren) - children = append(children, name) - if sep != nil { - children = append(children, sep) - } - children = append(children, val) - - return &MessageFieldNode{ - compositeNode: compositeNode{ - children: children, - }, - Name: name, - Sep: sep, - Val: val, - } -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/walk.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/walk.go deleted file mode 100644 index e9b850647..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/ast/walk.go +++ /dev/null @@ -1,497 +0,0 @@ -package ast - -// VisitFunc is used to examine a node in the AST when walking the tree. -// It returns true or false as to whether or not the descendants of the -// given node should be visited. If it returns true, the node's children -// will be visisted; if false, they will not. When returning true, it -// can also return a new VisitFunc to use for the children. If it returns -// (true, nil), then the current function will be re-used when visiting -// the children. -// -// See also the Visitor type. -type VisitFunc func(Node) (bool, VisitFunc) - -// Walk conducts a walk of the AST rooted at the given root using the -// given function. It performs a "pre-order traversal", visiting a -// given AST node before it visits that node's descendants. -func Walk(root Node, v VisitFunc) { - ok, next := v(root) - if !ok { - return - } - if next != nil { - v = next - } - if comp, ok := root.(CompositeNode); ok { - for _, child := range comp.Children() { - Walk(child, v) - } - } -} - -// Visitor provides a technique for walking the AST that allows for -// dynamic dispatch, where a particular function is invoked based on -// the runtime type of the argument. -// -// It consists of a number of functions, each of which matches a -// concrete Node type. It also includes functions for sub-interfaces -// of Node and the Node interface itself, to be used as broader -// "catch all" functions. -// -// To use a visitor, provide a function for the node types of -// interest and pass visitor.Visit as the function to a Walk operation. -// When a node is traversed, the corresponding function field of -// the visitor is invoked, if not nil. If the function for a node's -// concrete type is nil/absent but the function for an interface it -// implements is present, that interface visit function will be used -// instead. If no matching function is present, the traversal will -// continue. If a matching function is present, it will be invoked -// and its response determines how the traversal proceeds. -// -// Every visit function returns (bool, *Visitor). If the bool returned -// is false, the visited node's descendants are skipped. Otherwise, -// traversal will continue into the node's children. If the returned -// visitor is nil, the current visitor will continue to be used. But -// if a non-nil visitor is returned, it will be used to visit the -// node's children. -type Visitor struct { - // VisitFileNode is invoked when visiting a *FileNode in the AST. - VisitFileNode func(*FileNode) (bool, *Visitor) - // VisitSyntaxNode is invoked when visiting a *SyntaxNode in the AST. - VisitSyntaxNode func(*SyntaxNode) (bool, *Visitor) - - // TODO: add VisitEditionNode - - // VisitPackageNode is invoked when visiting a *PackageNode in the AST. - VisitPackageNode func(*PackageNode) (bool, *Visitor) - // VisitImportNode is invoked when visiting an *ImportNode in the AST. - VisitImportNode func(*ImportNode) (bool, *Visitor) - // VisitOptionNode is invoked when visiting an *OptionNode in the AST. - VisitOptionNode func(*OptionNode) (bool, *Visitor) - // VisitOptionNameNode is invoked when visiting an *OptionNameNode in the AST. - VisitOptionNameNode func(*OptionNameNode) (bool, *Visitor) - // VisitFieldReferenceNode is invoked when visiting a *FieldReferenceNode in the AST. - VisitFieldReferenceNode func(*FieldReferenceNode) (bool, *Visitor) - // VisitCompactOptionsNode is invoked when visiting a *CompactOptionsNode in the AST. - VisitCompactOptionsNode func(*CompactOptionsNode) (bool, *Visitor) - // VisitMessageNode is invoked when visiting a *MessageNode in the AST. - VisitMessageNode func(*MessageNode) (bool, *Visitor) - // VisitExtendNode is invoked when visiting an *ExtendNode in the AST. - VisitExtendNode func(*ExtendNode) (bool, *Visitor) - // VisitExtensionRangeNode is invoked when visiting an *ExtensionRangeNode in the AST. - VisitExtensionRangeNode func(*ExtensionRangeNode) (bool, *Visitor) - // VisitReservedNode is invoked when visiting a *ReservedNode in the AST. - VisitReservedNode func(*ReservedNode) (bool, *Visitor) - // VisitRangeNode is invoked when visiting a *RangeNode in the AST. - VisitRangeNode func(*RangeNode) (bool, *Visitor) - // VisitFieldNode is invoked when visiting a *FieldNode in the AST. - VisitFieldNode func(*FieldNode) (bool, *Visitor) - // VisitGroupNode is invoked when visiting a *GroupNode in the AST. - VisitGroupNode func(*GroupNode) (bool, *Visitor) - // VisitMapFieldNode is invoked when visiting a *MapFieldNode in the AST. - VisitMapFieldNode func(*MapFieldNode) (bool, *Visitor) - // VisitMapTypeNode is invoked when visiting a *MapTypeNode in the AST. - VisitMapTypeNode func(*MapTypeNode) (bool, *Visitor) - // VisitOneOfNode is invoked when visiting a *OneOfNode in the AST. - VisitOneOfNode func(*OneOfNode) (bool, *Visitor) - // VisitEnumNode is invoked when visiting an *EnumNode in the AST. - VisitEnumNode func(*EnumNode) (bool, *Visitor) - // VisitEnumValueNode is invoked when visiting an *EnumValueNode in the AST. - VisitEnumValueNode func(*EnumValueNode) (bool, *Visitor) - // VisitServiceNode is invoked when visiting a *ServiceNode in the AST. - VisitServiceNode func(*ServiceNode) (bool, *Visitor) - // VisitRPCNode is invoked when visiting an *RPCNode in the AST. - VisitRPCNode func(*RPCNode) (bool, *Visitor) - // VisitRPCTypeNode is invoked when visiting an *RPCTypeNode in the AST. - VisitRPCTypeNode func(*RPCTypeNode) (bool, *Visitor) - // VisitIdentNode is invoked when visiting an *IdentNode in the AST. - VisitIdentNode func(*IdentNode) (bool, *Visitor) - // VisitCompoundIdentNode is invoked when visiting a *CompoundIdentNode in the AST. - VisitCompoundIdentNode func(*CompoundIdentNode) (bool, *Visitor) - // VisitStringLiteralNode is invoked when visiting a *StringLiteralNode in the AST. - VisitStringLiteralNode func(*StringLiteralNode) (bool, *Visitor) - // VisitCompoundStringLiteralNode is invoked when visiting a *CompoundStringLiteralNode in the AST. - VisitCompoundStringLiteralNode func(*CompoundStringLiteralNode) (bool, *Visitor) - // VisitUintLiteralNode is invoked when visiting a *UintLiteralNode in the AST. - VisitUintLiteralNode func(*UintLiteralNode) (bool, *Visitor) - // VisitPositiveUintLiteralNode is invoked when visiting a *PositiveUintLiteralNode in the AST. - // - // Deprecated: this node type will not actually be present in an AST. - VisitPositiveUintLiteralNode func(*PositiveUintLiteralNode) (bool, *Visitor) - // VisitNegativeIntLiteralNode is invoked when visiting a *NegativeIntLiteralNode in the AST. - VisitNegativeIntLiteralNode func(*NegativeIntLiteralNode) (bool, *Visitor) - // VisitFloatLiteralNode is invoked when visiting a *FloatLiteralNode in the AST. - VisitFloatLiteralNode func(*FloatLiteralNode) (bool, *Visitor) - // VisitSpecialFloatLiteralNode is invoked when visiting a *SpecialFloatLiteralNode in the AST. - VisitSpecialFloatLiteralNode func(*SpecialFloatLiteralNode) (bool, *Visitor) - // VisitSignedFloatLiteralNode is invoked when visiting a *SignedFloatLiteralNode in the AST. - VisitSignedFloatLiteralNode func(*SignedFloatLiteralNode) (bool, *Visitor) - // VisitBoolLiteralNode is invoked when visiting a *BoolLiteralNode in the AST. - VisitBoolLiteralNode func(*BoolLiteralNode) (bool, *Visitor) - // VisitArrayLiteralNode is invoked when visiting an *ArrayLiteralNode in the AST. - VisitArrayLiteralNode func(*ArrayLiteralNode) (bool, *Visitor) - // VisitMessageLiteralNode is invoked when visiting a *MessageLiteralNode in the AST. - VisitMessageLiteralNode func(*MessageLiteralNode) (bool, *Visitor) - // VisitMessageFieldNode is invoked when visiting a *MessageFieldNode in the AST. - VisitMessageFieldNode func(*MessageFieldNode) (bool, *Visitor) - // VisitKeywordNode is invoked when visiting a *KeywordNode in the AST. - VisitKeywordNode func(*KeywordNode) (bool, *Visitor) - // VisitRuneNode is invoked when visiting a *RuneNode in the AST. - VisitRuneNode func(*RuneNode) (bool, *Visitor) - // VisitEmptyDeclNode is invoked when visiting a *EmptyDeclNode in the AST. - VisitEmptyDeclNode func(*EmptyDeclNode) (bool, *Visitor) - - // VisitFieldDeclNode is invoked when visiting a FieldDeclNode in the AST. - // This function is used when no concrete type function is provided. If - // both this and VisitMessageDeclNode are provided, and a node implements - // both (such as *GroupNode and *MapFieldNode), this function will be - // invoked and not the other. - VisitFieldDeclNode func(FieldDeclNode) (bool, *Visitor) - // VisitMessageDeclNode is invoked when visiting a MessageDeclNode in the AST. - // This function is used when no concrete type function is provided. - VisitMessageDeclNode func(MessageDeclNode) (bool, *Visitor) - - // VisitIdentValueNode is invoked when visiting an IdentValueNode in the AST. - // This function is used when no concrete type function is provided. - VisitIdentValueNode func(IdentValueNode) (bool, *Visitor) - // VisitStringValueNode is invoked when visiting a StringValueNode in the AST. - // This function is used when no concrete type function is provided. - VisitStringValueNode func(StringValueNode) (bool, *Visitor) - // VisitIntValueNode is invoked when visiting an IntValueNode in the AST. - // This function is used when no concrete type function is provided. If - // both this and VisitFloatValueNode are provided, and a node implements - // both (such as *UintLiteralNode), this function will be invoked and - // not the other. - VisitIntValueNode func(IntValueNode) (bool, *Visitor) - // VisitFloatValueNode is invoked when visiting a FloatValueNode in the AST. - // This function is used when no concrete type function is provided. - VisitFloatValueNode func(FloatValueNode) (bool, *Visitor) - // VisitValueNode is invoked when visiting a ValueNode in the AST. This - // function is used when no concrete type function is provided and no - // more specific ValueNode function is provided that matches the node. - VisitValueNode func(ValueNode) (bool, *Visitor) - - // VisitTerminalNode is invoked when visiting a TerminalNode in the AST. - // This function is used when no concrete type function is provided - // no more specific interface type function is provided. - VisitTerminalNode func(TerminalNode) (bool, *Visitor) - // VisitCompositeNode is invoked when visiting a CompositeNode in the AST. - // This function is used when no concrete type function is provided - // no more specific interface type function is provided. - VisitCompositeNode func(CompositeNode) (bool, *Visitor) - // VisitNode is invoked when visiting a Node in the AST. This - // function is only used when no other more specific function is - // provided. - VisitNode func(Node) (bool, *Visitor) -} - -// Visit provides the Visitor's implementation of VisitFunc, to be -// used with Walk operations. -func (v *Visitor) Visit(n Node) (bool, VisitFunc) { - var ok, matched bool - var next *Visitor - switch n := n.(type) { - case *FileNode: - if v.VisitFileNode != nil { - matched = true - ok, next = v.VisitFileNode(n) - } - case *SyntaxNode: - if v.VisitSyntaxNode != nil { - matched = true - ok, next = v.VisitSyntaxNode(n) - } - case *PackageNode: - if v.VisitPackageNode != nil { - matched = true - ok, next = v.VisitPackageNode(n) - } - case *ImportNode: - if v.VisitImportNode != nil { - matched = true - ok, next = v.VisitImportNode(n) - } - case *OptionNode: - if v.VisitOptionNode != nil { - matched = true - ok, next = v.VisitOptionNode(n) - } - case *OptionNameNode: - if v.VisitOptionNameNode != nil { - matched = true - ok, next = v.VisitOptionNameNode(n) - } - case *FieldReferenceNode: - if v.VisitFieldReferenceNode != nil { - matched = true - ok, next = v.VisitFieldReferenceNode(n) - } - case *CompactOptionsNode: - if v.VisitCompactOptionsNode != nil { - matched = true - ok, next = v.VisitCompactOptionsNode(n) - } - case *MessageNode: - if v.VisitMessageNode != nil { - matched = true - ok, next = v.VisitMessageNode(n) - } - case *ExtendNode: - if v.VisitExtendNode != nil { - matched = true - ok, next = v.VisitExtendNode(n) - } - case *ExtensionRangeNode: - if v.VisitExtensionRangeNode != nil { - matched = true - ok, next = v.VisitExtensionRangeNode(n) - } - case *ReservedNode: - if v.VisitReservedNode != nil { - matched = true - ok, next = v.VisitReservedNode(n) - } - case *RangeNode: - if v.VisitRangeNode != nil { - matched = true - ok, next = v.VisitRangeNode(n) - } - case *FieldNode: - if v.VisitFieldNode != nil { - matched = true - ok, next = v.VisitFieldNode(n) - } - case *GroupNode: - if v.VisitGroupNode != nil { - matched = true - ok, next = v.VisitGroupNode(n) - } - case *MapFieldNode: - if v.VisitMapFieldNode != nil { - matched = true - ok, next = v.VisitMapFieldNode(n) - } - case *MapTypeNode: - if v.VisitMapTypeNode != nil { - matched = true - ok, next = v.VisitMapTypeNode(n) - } - case *OneOfNode: - if v.VisitOneOfNode != nil { - matched = true - ok, next = v.VisitOneOfNode(n) - } - case *EnumNode: - if v.VisitEnumNode != nil { - matched = true - ok, next = v.VisitEnumNode(n) - } - case *EnumValueNode: - if v.VisitEnumValueNode != nil { - matched = true - ok, next = v.VisitEnumValueNode(n) - } - case *ServiceNode: - if v.VisitServiceNode != nil { - matched = true - ok, next = v.VisitServiceNode(n) - } - case *RPCNode: - if v.VisitRPCNode != nil { - matched = true - ok, next = v.VisitRPCNode(n) - } - case *RPCTypeNode: - if v.VisitRPCTypeNode != nil { - matched = true - ok, next = v.VisitRPCTypeNode(n) - } - case *IdentNode: - if v.VisitIdentNode != nil { - matched = true - ok, next = v.VisitIdentNode(n) - } - case *CompoundIdentNode: - if v.VisitCompoundIdentNode != nil { - matched = true - ok, next = v.VisitCompoundIdentNode(n) - } - case *StringLiteralNode: - if v.VisitStringLiteralNode != nil { - matched = true - ok, next = v.VisitStringLiteralNode(n) - } - case *CompoundStringLiteralNode: - if v.VisitCompoundStringLiteralNode != nil { - matched = true - ok, next = v.VisitCompoundStringLiteralNode(n) - } - case *UintLiteralNode: - if v.VisitUintLiteralNode != nil { - matched = true - ok, next = v.VisitUintLiteralNode(n) - } - case *PositiveUintLiteralNode: - if v.VisitPositiveUintLiteralNode != nil { - matched = true - ok, next = v.VisitPositiveUintLiteralNode(n) - } - case *NegativeIntLiteralNode: - if v.VisitNegativeIntLiteralNode != nil { - matched = true - ok, next = v.VisitNegativeIntLiteralNode(n) - } - case *FloatLiteralNode: - if v.VisitFloatLiteralNode != nil { - matched = true - ok, next = v.VisitFloatLiteralNode(n) - } - case *SpecialFloatLiteralNode: - if v.VisitSpecialFloatLiteralNode != nil { - matched = true - ok, next = v.VisitSpecialFloatLiteralNode(n) - } - case *SignedFloatLiteralNode: - if v.VisitSignedFloatLiteralNode != nil { - matched = true - ok, next = v.VisitSignedFloatLiteralNode(n) - } - case *BoolLiteralNode: - if v.VisitBoolLiteralNode != nil { - matched = true - ok, next = v.VisitBoolLiteralNode(n) - } - case *ArrayLiteralNode: - if v.VisitArrayLiteralNode != nil { - matched = true - ok, next = v.VisitArrayLiteralNode(n) - } - case *MessageLiteralNode: - if v.VisitMessageLiteralNode != nil { - matched = true - ok, next = v.VisitMessageLiteralNode(n) - } - case *MessageFieldNode: - if v.VisitMessageFieldNode != nil { - matched = true - ok, next = v.VisitMessageFieldNode(n) - } - case *KeywordNode: - if v.VisitKeywordNode != nil { - matched = true - ok, next = v.VisitKeywordNode(n) - } - case *RuneNode: - if v.VisitRuneNode != nil { - matched = true - ok, next = v.VisitRuneNode(n) - } - case *EmptyDeclNode: - if v.VisitEmptyDeclNode != nil { - matched = true - ok, next = v.VisitEmptyDeclNode(n) - } - } - - if !matched { - // Visitor provided no concrete type visit function, so - // check interface types. We do this in several passes - // to provide "priority" for matched interfaces for nodes - // that actually implement more than one interface. - // - // For example, StringLiteralNode implements both - // StringValueNode and ValueNode. Both cases could match - // so the first case is what would match. So if we want - // to test against either, they need to be in different - // switch statements. - switch n := n.(type) { - case FieldDeclNode: - if v.VisitFieldDeclNode != nil { - matched = true - ok, next = v.VisitFieldDeclNode(n) - } - case IdentValueNode: - if v.VisitIdentValueNode != nil { - matched = true - ok, next = v.VisitIdentValueNode(n) - } - case StringValueNode: - if v.VisitStringValueNode != nil { - matched = true - ok, next = v.VisitStringValueNode(n) - } - case IntValueNode: - if v.VisitIntValueNode != nil { - matched = true - ok, next = v.VisitIntValueNode(n) - } - } - } - - if !matched { - // These two are excluded from the above switch so that - // if visitor provides both VisitIntValueNode and - // VisitFloatValueNode, we'll prefer VisitIntValueNode - // for *UintLiteralNode (which implements both). Similarly, - // that way we prefer VisitFieldDeclNode over - // VisitMessageDeclNode when visiting a *GroupNode. - switch n := n.(type) { - case FloatValueNode: - if v.VisitFloatValueNode != nil { - matched = true - ok, next = v.VisitFloatValueNode(n) - } - case MessageDeclNode: - if v.VisitMessageDeclNode != nil { - matched = true - ok, next = v.VisitMessageDeclNode(n) - } - } - } - - if !matched { - switch n := n.(type) { - case ValueNode: - if v.VisitValueNode != nil { - matched = true - ok, next = v.VisitValueNode(n) - } - } - } - - if !matched { - switch n := n.(type) { - case TerminalNode: - if v.VisitTerminalNode != nil { - matched = true - ok, next = v.VisitTerminalNode(n) - } - case CompositeNode: - if v.VisitCompositeNode != nil { - matched = true - ok, next = v.VisitCompositeNode(n) - } - } - } - - if !matched { - // finally, fallback to most generic visit function - if v.VisitNode != nil { - matched = true - ok, next = v.VisitNode(n) - } - } - - if !matched { - // keep descending with the current visitor - return true, nil - } - - if !ok { - return false, nil - } - if next != nil { - return true, next.Visit - } - return true, v.Visit -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/doc.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/doc.go deleted file mode 100644 index 6642f6a4c..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -// Package protoparse provides functionality for parsing *.proto source files -// into descriptors that can be used with other protoreflect packages, like -// dynamic messages and dynamic GRPC clients. -// -// This package links in other packages that include compiled descriptors for -// the various "google/protobuf/*.proto" files that are included with protoc. -// That way, like when invoking protoc, programs need not supply copies of these -// "builtin" files. Though if copies of the files are provided, they will be -// used instead of the builtin descriptors. -// -// Deprecated: This protoparse package is now just a thin veneer around a newer -// replacement parser/compiler: [github.com/bufbuild/protocompile]. Users are -// highly encouraged to directly use protocompile instead of this package. -// -// [github.com/bufbuild/protocompile]: https://pkg.go.dev/github.com/bufbuild/protocompile -package protoparse diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/errors.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/errors.go deleted file mode 100644 index 0ec70bd75..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/errors.go +++ /dev/null @@ -1,122 +0,0 @@ -package protoparse - -import ( - "errors" - "fmt" - - "github.com/bufbuild/protocompile/linker" - "github.com/bufbuild/protocompile/parser" - "github.com/bufbuild/protocompile/reporter" - - "github.com/jhump/protoreflect/desc/protoparse/ast" -) - -// SourcePos is the same as ast.SourcePos. This alias exists for -// backwards compatibility (SourcePos used to be defined in this package.) -type SourcePos = ast.SourcePos - -// ErrInvalidSource is a sentinel error that is returned by calls to -// Parser.ParseFiles and Parser.ParseFilesButDoNotLink in the event that syntax -// or link errors are encountered, but the parser's configured ErrorReporter -// always returns nil. -var ErrInvalidSource = reporter.ErrInvalidSource - -// ErrNoSyntax is a sentinel error that may be passed to a warning reporter. -// The error the reporter receives will be wrapped with source position that -// indicates the file that had no syntax statement. -var ErrNoSyntax = parser.ErrNoSyntax - -// ErrLookupImportAndProtoSet is the error returned if both LookupImport and LookupImportProto are set. -// -// Deprecated: This error is no longer used. It is now legal to set both LookupImport and LookupImportProto -// fields on the Parser. -var ErrLookupImportAndProtoSet = errors.New("both LookupImport and LookupImportProto set") - -// ErrorReporter is responsible for reporting the given error. If the reporter -// returns a non-nil error, parsing/linking will abort with that error. If the -// reporter returns nil, parsing will continue, allowing the parser to try to -// report as many syntax and/or link errors as it can find. -type ErrorReporter = reporter.ErrorReporter - -// WarningReporter is responsible for reporting the given warning. This is used -// for indicating non-error messages to the calling program for things that do -// not cause the parse to fail but are considered bad practice. Though they are -// just warnings, the details are supplied to the reporter via an error type. -type WarningReporter = reporter.WarningReporter - -// ErrorWithPos is an error about a proto source file that includes information -// about the location in the file that caused the error. -// -// The value of Error() will contain both the SourcePos and Underlying error. -// The value of Unwrap() will only be the Underlying error. -type ErrorWithPos = reporter.ErrorWithPos - -// ErrorWithSourcePos is an error about a proto source file that includes -// information about the location in the file that caused the error. -// -// Errors that include source location information *might* be of this type. -// However, calling code that is trying to examine errors with location info -// should instead look for instances of the ErrorWithPos interface, which -// will find other kinds of errors. This type is only exported for backwards -// compatibility. -// -// SourcePos should always be set and never nil. -type ErrorWithSourcePos struct { - // These fields are present and exported for backwards-compatibility - // with v1.4 and earlier. - Underlying error - Pos *SourcePos - - reporter.ErrorWithPos -} - -// Error implements the error interface -func (e ErrorWithSourcePos) Error() string { - sourcePos := e.GetPosition() - return fmt.Sprintf("%s: %v", sourcePos, e.Underlying) -} - -// GetPosition implements the ErrorWithPos interface, supplying a location in -// proto source that caused the error. -func (e ErrorWithSourcePos) GetPosition() SourcePos { - if e.Pos == nil { - return SourcePos{Filename: ""} - } - return *e.Pos -} - -// Unwrap implements the ErrorWithPos interface, supplying the underlying -// error. This error will not include location information. -func (e ErrorWithSourcePos) Unwrap() error { - return e.Underlying -} - -var _ ErrorWithPos = ErrorWithSourcePos{} - -func toErrorWithSourcePos(err ErrorWithPos) ErrorWithPos { - pos := err.GetPosition() - return ErrorWithSourcePos{ - ErrorWithPos: err, - Underlying: err.Unwrap(), - Pos: &pos, - } -} - -// ErrorUnusedImport may be passed to a warning reporter when an unused -// import is detected. The error the reporter receives will be wrapped -// with source position that indicates the file and line where the import -// statement appeared. -type ErrorUnusedImport = linker.ErrorUnusedImport - -type errorWithFilename struct { - underlying error - filename string -} - -func (e errorWithFilename) Error() string { - return fmt.Sprintf("%s: %v", e.filename, e.underlying) -} - -func (e errorWithFilename) Unwrap() error { - return e.underlying -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/parser.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/parser.go deleted file mode 100644 index 1a6763dfa..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/parser.go +++ /dev/null @@ -1,804 +0,0 @@ -package protoparse - -import ( - "context" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/bufbuild/protocompile" - ast2 "github.com/bufbuild/protocompile/ast" - "github.com/bufbuild/protocompile/linker" - "github.com/bufbuild/protocompile/options" - "github.com/bufbuild/protocompile/parser" - "github.com/bufbuild/protocompile/protoutil" - "github.com/bufbuild/protocompile/reporter" - "github.com/bufbuild/protocompile/sourceinfo" - "github.com/bufbuild/protocompile/walk" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/types/descriptorpb" - - "github.com/jhump/protoreflect/desc" - "github.com/jhump/protoreflect/desc/internal" - "github.com/jhump/protoreflect/desc/protoparse/ast" -) - -// FileAccessor is an abstraction for opening proto source files. It takes the -// name of the file to open and returns either the input reader or an error. -type FileAccessor func(filename string) (io.ReadCloser, error) - -// FileContentsFromMap returns a FileAccessor that uses the given map of file -// contents. This allows proto source files to be constructed in memory and -// easily supplied to a parser. The map keys are the paths to the proto source -// files, and the values are the actual proto source contents. -func FileContentsFromMap(files map[string]string) FileAccessor { - return func(filename string) (io.ReadCloser, error) { - contents, ok := files[filename] - if !ok { - // Try changing path separators since user-provided - // map may use different separators. - contents, ok = files[filepath.ToSlash(filename)] - if !ok { - return nil, os.ErrNotExist - } - } - return ioutil.NopCloser(strings.NewReader(contents)), nil - } -} - -// Parser parses proto source into descriptors. -type Parser struct { - // The paths used to search for dependencies that are referenced in import - // statements in proto source files. If no import paths are provided then - // "." (current directory) is assumed to be the only import path. - // - // This setting is only used during ParseFiles operations. Since calls to - // ParseFilesButDoNotLink do not link, there is no need to load and parse - // dependencies. - ImportPaths []string - - // If true, the supplied file names/paths need not necessarily match how the - // files are referenced in import statements. The parser will attempt to - // match import statements to supplied paths, "guessing" the import paths - // for the files. Note that this inference is not perfect and link errors - // could result. It works best when all proto files are organized such that - // a single import path can be inferred (e.g. all files under a single tree - // with import statements all being relative to the root of this tree). - InferImportPaths bool - - // LookupImport is a function that accepts a filename and - // returns a file descriptor, which will be consulted when resolving imports. - // This allows a compiled Go proto in another Go module to be referenced - // in the proto(s) being parsed. - // - // In the event of a filename collision, Accessor is consulted first, - // then LookupImport is consulted, and finally the well-known protos - // are used. - // - // For example, in order to automatically look up compiled Go protos that - // have been imported and be able to use them as imports, set this to - // desc.LoadFileDescriptor. - LookupImport func(string) (*desc.FileDescriptor, error) - - // LookupImportProto has the same functionality as LookupImport, however it returns - // a FileDescriptorProto instead of a FileDescriptor. - LookupImportProto func(string) (*descriptorpb.FileDescriptorProto, error) - - // Used to create a reader for a given filename, when loading proto source - // file contents. If unset, os.Open is used. If ImportPaths is also empty - // then relative paths are will be relative to the process's current working - // directory. - Accessor FileAccessor - - // If true, the resulting file descriptors will retain source code info, - // that maps elements to their location in the source files as well as - // includes comments found during parsing (and attributed to elements of - // the source file). - IncludeSourceCodeInfo bool - - // If true, the results from ParseFilesButDoNotLink will be passed through - // some additional validations. But only constraints that do not require - // linking can be checked. These include proto2 vs. proto3 language features, - // looking for incorrect usage of reserved names or tags, and ensuring that - // fields have unique tags and that enum values have unique numbers (unless - // the enum allows aliases). - ValidateUnlinkedFiles bool - - // If true, the results from ParseFilesButDoNotLink will have options - // interpreted. Any uninterpretable options (including any custom options or - // options that refer to message and enum types, which can only be - // interpreted after linking) will be left in uninterpreted_options. Also, - // the "default" pseudo-option for fields can only be interpreted for scalar - // fields, excluding enums. (Interpreting default values for enum fields - // requires resolving enum names, which requires linking.) - InterpretOptionsInUnlinkedFiles bool - - // A custom reporter of syntax and link errors. If not specified, the - // default reporter just returns the reported error, which causes parsing - // to abort after encountering a single error. - // - // The reporter is not invoked for system or I/O errors, only for syntax and - // link errors. - ErrorReporter ErrorReporter - - // A custom reporter of warnings. If not specified, warning messages are ignored. - WarningReporter WarningReporter -} - -// ParseFiles parses the named files into descriptors. The returned slice has -// the same number of entries as the give filenames, in the same order. So the -// first returned descriptor corresponds to the first given name, and so on. -// -// All dependencies for all specified files (including transitive dependencies) -// must be accessible via the parser's Accessor or a link error will occur. The -// exception to this rule is that files can import standard Google-provided -// files -- e.g. google/protobuf/*.proto -- without needing to supply sources -// for these files. Like protoc, this parser has a built-in version of these -// files it can use if they aren't explicitly supplied. -// -// If the Parser has no ErrorReporter set and a syntax or link error occurs, -// parsing will abort with the first such error encountered. If there is an -// ErrorReporter configured and it returns non-nil, parsing will abort with the -// error it returns. If syntax or link errors are encountered but the configured -// ErrorReporter always returns nil, the parse fails with ErrInvalidSource. -func (p Parser) ParseFiles(filenames ...string) ([]*desc.FileDescriptor, error) { - srcInfoMode := protocompile.SourceInfoNone - if p.IncludeSourceCodeInfo { - srcInfoMode = protocompile.SourceInfoExtraComments - } - rep := newReporter(p.ErrorReporter, p.WarningReporter) - res, srcSpanAddr := p.getResolver(filenames) - - if p.InferImportPaths { - // we must first compile everything to protos - results, err := parseToProtosRecursive(res, filenames, reporter.NewHandler(rep), srcSpanAddr) - if err != nil { - return nil, err - } - // then we can infer import paths - var rewritten map[string]string - results, rewritten = fixupFilenames(results) - if len(rewritten) > 0 { - for i := range filenames { - if replace, ok := rewritten[filenames[i]]; ok { - filenames[i] = replace - } - } - } - resolverFromResults := protocompile.ResolverFunc(func(path string) (protocompile.SearchResult, error) { - res, ok := results[path] - if !ok { - return protocompile.SearchResult{}, os.ErrNotExist - } - return protocompile.SearchResult{ParseResult: noCloneParseResult{res}}, nil - }) - res = protocompile.CompositeResolver{resolverFromResults, res} - } - - c := protocompile.Compiler{ - Resolver: res, - MaxParallelism: 1, - SourceInfoMode: srcInfoMode, - Reporter: rep, - } - results, err := c.Compile(context.Background(), filenames...) - if err != nil { - return nil, err - } - - fds := make([]protoreflect.FileDescriptor, len(results)) - alreadySeen := make(map[string]struct{}, len(results)) - for i, res := range results { - removeDynamicExtensions(res, alreadySeen) - fds[i] = res - } - return desc.WrapFiles(fds) -} - -type noCloneParseResult struct { - parser.Result -} - -func (r noCloneParseResult) Clone() parser.Result { - // protocompile will clone parser.Result to make sure it can't be shared - // with other compilation operations (which would not be thread-safe). - // However, this parse result cannot be shared with another compile - // operation. That means the clone is unnecessary; so we skip it, to avoid - // the associated performance costs. - return r.Result -} - -// ParseFilesButDoNotLink parses the named files into descriptor protos. The -// results are just protos, not fully-linked descriptors. It is possible that -// descriptors are invalid and still be returned in parsed form without error -// due to the fact that the linking step is skipped (and thus many validation -// steps omitted). -// -// There are a few side effects to not linking the descriptors: -// 1. No options will be interpreted. Options can refer to extensions or have -// message and enum types. Without linking, these extension and type -// references are not resolved, so the options may not be interpretable. -// So all options will appear in UninterpretedOption fields of the various -// descriptor options messages. -// 2. Type references will not be resolved. This means that the actual type -// names in the descriptors may be unqualified and even relative to the -// scope in which the type reference appears. This goes for fields that -// have message and enum types. It also applies to methods and their -// references to request and response message types. -// 3. Type references are not known. For non-scalar fields, until the type -// name is resolved (during linking), it is not known whether the type -// refers to a message or an enum. So all fields with such type references -// will not have their Type set, only the TypeName. -// -// This method will still validate the syntax of parsed files. If the parser's -// ValidateUnlinkedFiles field is true, additional checks, beyond syntax will -// also be performed. -// -// If the Parser has no ErrorReporter set and a syntax error occurs, parsing -// will abort with the first such error encountered. If there is an -// ErrorReporter configured and it returns non-nil, parsing will abort with the -// error it returns. If syntax errors are encountered but the configured -// ErrorReporter always returns nil, the parse fails with ErrInvalidSource. -func (p Parser) ParseFilesButDoNotLink(filenames ...string) ([]*descriptorpb.FileDescriptorProto, error) { - rep := newReporter(p.ErrorReporter, p.WarningReporter) - p.ImportPaths = nil // not used for this "do not link" operation. - res, _ := p.getResolver(filenames) - results, err := parseToProtos(res, filenames, reporter.NewHandler(rep), p.ValidateUnlinkedFiles) - if err != nil { - return nil, err - } - - if p.InferImportPaths { - resultsMap := make(map[string]parser.Result, len(results)) - for _, res := range results { - resultsMap[res.FileDescriptorProto().GetName()] = res - } - var rewritten map[string]string - resultsMap, rewritten = fixupFilenames(resultsMap) - if len(rewritten) > 0 { - for i := range filenames { - if replace, ok := rewritten[filenames[i]]; ok { - filenames[i] = replace - } - } - } - for i := range filenames { - results[i] = resultsMap[filenames[i]] - } - } - - protos := make([]*descriptorpb.FileDescriptorProto, len(results)) - for i, res := range results { - protos[i] = res.FileDescriptorProto() - var optsIndex sourceinfo.OptionIndex - if p.InterpretOptionsInUnlinkedFiles { - var err error - optsIndex, err = options.InterpretUnlinkedOptions(res) - if err != nil { - return nil, err - } - removeDynamicExtensionsFromProto(protos[i]) - } - if p.IncludeSourceCodeInfo { - protos[i].SourceCodeInfo = sourceinfo.GenerateSourceInfo(res.AST(), optsIndex, sourceinfo.WithExtraComments()) - } - } - - return protos, nil -} - -// ParseToAST parses the named files into ASTs, or Abstract Syntax Trees. This -// is for consumers of proto files that don't care about compiling the files to -// descriptors, but care deeply about a non-lossy structured representation of -// the source (since descriptors are lossy). This includes formatting tools and -// possibly linters, too. -// -// If the requested filenames include standard imports (such as -// "google/protobuf/empty.proto") and no source is provided, the corresponding -// AST in the returned slice will be nil. These standard imports are only -// available for use as descriptors; no source is available unless it is -// provided by the configured Accessor. -// -// If the Parser has no ErrorReporter set and a syntax error occurs, parsing -// will abort with the first such error encountered. If there is an -// ErrorReporter configured and it returns non-nil, parsing will abort with the -// error it returns. If syntax errors are encountered but the configured -// ErrorReporter always returns nil, the parse fails with ErrInvalidSource. -func (p Parser) ParseToAST(filenames ...string) ([]*ast.FileNode, error) { - rep := newReporter(p.ErrorReporter, p.WarningReporter) - res, _ := p.getResolver(filenames) - asts, _, err := parseToASTs(res, filenames, reporter.NewHandler(rep)) - if err != nil { - return nil, err - } - results := make([]*ast.FileNode, len(asts)) - for i := range asts { - if asts[i] == nil { - // should not be possible but... - return nil, fmt.Errorf("resolver did not produce source for %v", filenames[i]) - } - results[i] = convertAST(asts[i]) - } - return results, nil -} - -func parseToAST(res protocompile.Resolver, filename string, rep *reporter.Handler) (*ast2.FileNode, parser.Result, error) { - searchResult, err := res.FindFileByPath(filename) - if err != nil { - _ = rep.HandleError(err) - return nil, nil, rep.Error() - } - switch { - case searchResult.ParseResult != nil: - return nil, searchResult.ParseResult, nil - case searchResult.Proto != nil: - return nil, parser.ResultWithoutAST(searchResult.Proto), nil - case searchResult.Desc != nil: - return nil, parser.ResultWithoutAST(protoutil.ProtoFromFileDescriptor(searchResult.Desc)), nil - case searchResult.AST != nil: - return searchResult.AST, nil, nil - case searchResult.Source != nil: - astRoot, err := parser.Parse(filename, searchResult.Source, rep) - return astRoot, nil, err - default: - _ = rep.HandleError(fmt.Errorf("resolver did not produce a result for %v", filename)) - return nil, nil, rep.Error() - } -} - -func parseToASTs(res protocompile.Resolver, filenames []string, rep *reporter.Handler) ([]*ast2.FileNode, []parser.Result, error) { - asts := make([]*ast2.FileNode, len(filenames)) - results := make([]parser.Result, len(filenames)) - for i := range filenames { - asts[i], results[i], _ = parseToAST(res, filenames[i], rep) - if rep.ReporterError() != nil { - break - } - } - return asts, results, rep.Error() -} - -func parseToProtos(res protocompile.Resolver, filenames []string, rep *reporter.Handler, validate bool) ([]parser.Result, error) { - asts, results, err := parseToASTs(res, filenames, rep) - if err != nil { - return nil, err - } - for i := range results { - if results[i] != nil { - continue - } - var err error - results[i], err = parser.ResultFromAST(asts[i], validate, rep) - if err != nil { - return nil, err - } - } - return results, nil -} - -func parseToProtosRecursive(res protocompile.Resolver, filenames []string, rep *reporter.Handler, srcSpanAddr *ast2.SourceSpan) (map[string]parser.Result, error) { - results := make(map[string]parser.Result, len(filenames)) - for _, filename := range filenames { - if err := parseToProtoRecursive(res, filename, rep, srcSpanAddr, results); err != nil { - return results, err - } - } - return results, rep.Error() -} - -func parseToProtoRecursive(res protocompile.Resolver, filename string, rep *reporter.Handler, srcSpanAddr *ast2.SourceSpan, results map[string]parser.Result) error { - if _, ok := results[filename]; ok { - // already processed this one - return nil - } - results[filename] = nil // placeholder entry - - astRoot, parseResult, err := parseToAST(res, filename, rep) - if err != nil { - return err - } - if parseResult == nil { - parseResult, err = parser.ResultFromAST(astRoot, true, rep) - if err != nil { - return err - } - } - results[filename] = parseResult - - if astRoot != nil { - // We have an AST, so we use it to recursively examine imports. - for _, decl := range astRoot.Decls { - imp, ok := decl.(*ast2.ImportNode) - if !ok { - continue - } - err := func() error { - orig := *srcSpanAddr - *srcSpanAddr = astRoot.NodeInfo(imp.Name) - defer func() { - *srcSpanAddr = orig - }() - - return parseToProtoRecursive(res, imp.Name.AsString(), rep, srcSpanAddr, results) - }() - if err != nil { - return err - } - } - return nil - } - - // Without an AST, we must recursively examine the proto. This makes it harder - // (but not necessarily impossible) to get the source location of the import. - fd := parseResult.FileDescriptorProto() - for i, dep := range fd.Dependency { - path := []int32{internal.File_dependencyTag, int32(i)} - err := func() error { - orig := *srcSpanAddr - found := false - for _, loc := range fd.GetSourceCodeInfo().GetLocation() { - if pathsEqual(loc.Path, path) { - start := SourcePos{ - Filename: dep, - Line: int(loc.Span[0]), - Col: int(loc.Span[1]), - } - var end SourcePos - if len(loc.Span) > 3 { - end = SourcePos{ - Filename: dep, - Line: int(loc.Span[2]), - Col: int(loc.Span[3]), - } - } else { - end = SourcePos{ - Filename: dep, - Line: int(loc.Span[0]), - Col: int(loc.Span[2]), - } - } - *srcSpanAddr = ast2.NewSourceSpan(start, end) - found = true - break - } - } - if !found { - *srcSpanAddr = ast2.UnknownSpan(dep) - } - defer func() { - *srcSpanAddr = orig - }() - - return parseToProtoRecursive(res, dep, rep, srcSpanAddr, results) - }() - if err != nil { - return err - } - } - return nil -} - -func pathsEqual(a, b []int32) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -func newReporter(errRep ErrorReporter, warnRep WarningReporter) reporter.Reporter { - if errRep != nil { - delegate := errRep - errRep = func(err ErrorWithPos) error { - if _, ok := err.(ErrorWithSourcePos); !ok { - err = toErrorWithSourcePos(err) - } - return delegate(err) - } - } - if warnRep != nil { - delegate := warnRep - warnRep = func(err ErrorWithPos) { - if _, ok := err.(ErrorWithSourcePos); !ok { - err = toErrorWithSourcePos(err) - } - delegate(err) - } - } - return reporter.NewReporter(errRep, warnRep) -} - -func (p Parser) getResolver(filenames []string) (protocompile.Resolver, *ast2.SourceSpan) { - var srcSpan ast2.SourceSpan - accessor := p.Accessor - if accessor == nil { - accessor = func(name string) (io.ReadCloser, error) { - return os.Open(name) - } - } - sourceResolver := &protocompile.SourceResolver{ - Accessor: func(filename string) (io.ReadCloser, error) { - in, err := accessor(filename) - if err != nil { - if !strings.Contains(err.Error(), filename) { - // errors that don't include the filename that failed are no bueno - err = errorWithFilename{filename: filename, underlying: err} - } - if srcSpan != nil { - err = reporter.Error(srcSpan, err) - } - } - return in, err - }, - ImportPaths: p.ImportPaths, - } - var importResolver protocompile.CompositeResolver - if p.LookupImport != nil { - importResolver = append(importResolver, protocompile.ResolverFunc(func(path string) (protocompile.SearchResult, error) { - fd, err := p.LookupImport(path) - if err != nil { - return protocompile.SearchResult{}, err - } - return protocompile.SearchResult{Desc: fd.UnwrapFile()}, nil - })) - } - if p.LookupImportProto != nil { - importResolver = append(importResolver, protocompile.ResolverFunc(func(path string) (protocompile.SearchResult, error) { - fd, err := p.LookupImportProto(path) - if err != nil { - return protocompile.SearchResult{}, err - } - return protocompile.SearchResult{Proto: fd}, nil - })) - } - backupResolver := protocompile.WithStandardImports(importResolver) - return protocompile.CompositeResolver{ - sourceResolver, - protocompile.ResolverFunc(func(path string) (protocompile.SearchResult, error) { - return backupResolver.FindFileByPath(path) - }), - }, &srcSpan -} - -func fixupFilenames(protos map[string]parser.Result) (revisedProtos map[string]parser.Result, rewrittenPaths map[string]string) { - // In the event that the given filenames (keys in the supplied map) do not - // match the actual paths used in 'import' statements in the files, we try - // to revise names in the protos so that they will match and be linkable. - revisedProtos = make(map[string]parser.Result, len(protos)) - rewrittenPaths = make(map[string]string, len(protos)) - - protoPaths := map[string]struct{}{} - // TODO: this is O(n^2) but could likely be O(n) with a clever data structure (prefix tree that is indexed backwards?) - importCandidates := map[string]map[string]struct{}{} - candidatesAvailable := map[string]struct{}{} - for name := range protos { - candidatesAvailable[name] = struct{}{} - for _, f := range protos { - for _, imp := range f.FileDescriptorProto().Dependency { - if strings.HasSuffix(name, imp) || strings.HasSuffix(imp, name) { - candidates := importCandidates[imp] - if candidates == nil { - candidates = map[string]struct{}{} - importCandidates[imp] = candidates - } - candidates[name] = struct{}{} - } - } - } - } - for imp, candidates := range importCandidates { - // if we found multiple possible candidates, use the one that is an exact match - // if it exists, and otherwise, guess that it's the shortest path (fewest elements) - var best string - for c := range candidates { - if _, ok := candidatesAvailable[c]; !ok { - // already used this candidate and re-written its filename accordingly - continue - } - if c == imp { - // exact match! - best = c - break - } - if best == "" { - best = c - } else { - // NB: We can't actually tell which file is supposed to match - // this import. So we prefer the longest name. On a tie, we - // choose the lexically earliest match. - minLen := strings.Count(best, string(filepath.Separator)) - cLen := strings.Count(c, string(filepath.Separator)) - if cLen > minLen || (cLen == minLen && c < best) { - best = c - } - } - } - if best != "" { - if len(best) > len(imp) { - prefix := best[:len(best)-len(imp)] - protoPaths[prefix] = struct{}{} - } - f := protos[best] - f.FileDescriptorProto().Name = proto.String(imp) - revisedProtos[imp] = f - rewrittenPaths[best] = imp - delete(candidatesAvailable, best) - - // If other candidates are actually references to the same file, remove them. - for c := range candidates { - if _, ok := candidatesAvailable[c]; !ok { - // already used this candidate and re-written its filename accordingly - continue - } - possibleDup := protos[c] - prevName := possibleDup.FileDescriptorProto().Name - possibleDup.FileDescriptorProto().Name = proto.String(imp) - if !proto.Equal(f.FileDescriptorProto(), protos[c].FileDescriptorProto()) { - // not equal: restore name and look at next one - possibleDup.FileDescriptorProto().Name = prevName - continue - } - // This file used a different name but was actually the same file. So - // we prune it from the set. - rewrittenPaths[c] = imp - delete(candidatesAvailable, c) - if len(c) > len(imp) { - prefix := c[:len(c)-len(imp)] - protoPaths[prefix] = struct{}{} - } - } - } - } - - if len(candidatesAvailable) == 0 { - return revisedProtos, rewrittenPaths - } - - if len(protoPaths) == 0 { - for c := range candidatesAvailable { - revisedProtos[c] = protos[c] - } - return revisedProtos, rewrittenPaths - } - - // Any remaining candidates are entry-points (not imported by others), so - // the best bet to "fixing" their file name is to see if they're in one of - // the proto paths we found, and if so strip that prefix. - protoPathStrs := make([]string, len(protoPaths)) - i := 0 - for p := range protoPaths { - protoPathStrs[i] = p - i++ - } - sort.Strings(protoPathStrs) - // we look at paths in reverse order, so we'll use a longer proto path if - // there is more than one match - for c := range candidatesAvailable { - var imp string - for i := len(protoPathStrs) - 1; i >= 0; i-- { - p := protoPathStrs[i] - if strings.HasPrefix(c, p) { - imp = c[len(p):] - break - } - } - if imp != "" { - f := protos[c] - f.FileDescriptorProto().Name = proto.String(imp) - f.FileNode() - revisedProtos[imp] = f - rewrittenPaths[c] = imp - } else { - revisedProtos[c] = protos[c] - } - } - - return revisedProtos, rewrittenPaths -} - -func removeDynamicExtensions(fd protoreflect.FileDescriptor, alreadySeen map[string]struct{}) { - if _, ok := alreadySeen[fd.Path()]; ok { - // already processed - return - } - alreadySeen[fd.Path()] = struct{}{} - res, ok := fd.(linker.Result) - if ok { - removeDynamicExtensionsFromProto(res.FileDescriptorProto()) - } - // also remove extensions from dependencies - for i, length := 0, fd.Imports().Len(); i < length; i++ { - removeDynamicExtensions(fd.Imports().Get(i).FileDescriptor, alreadySeen) - } -} - -func removeDynamicExtensionsFromProto(fd *descriptorpb.FileDescriptorProto) { - // protocompile returns descriptors with dynamic extension fields for custom options. - // But protoparse only used known custom options and everything else defined in the - // sources would be stored as unrecognized fields. So to bridge the difference in - // behavior, we need to remove custom options from the given file and add them back - // via serializing-then-de-serializing them back into the options messages. That way, - // statically known options will be properly typed and others will be unrecognized. - // - // This is best effort. So if an error occurs, we'll still return a result, but it - // may include a dynamic extension. - fd.Options = removeDynamicExtensionsFromOptions(fd.Options) - _ = walk.DescriptorProtos(fd, func(_ protoreflect.FullName, msg proto.Message) error { - switch msg := msg.(type) { - case *descriptorpb.DescriptorProto: - msg.Options = removeDynamicExtensionsFromOptions(msg.Options) - for _, extr := range msg.ExtensionRange { - extr.Options = removeDynamicExtensionsFromOptions(extr.Options) - } - case *descriptorpb.FieldDescriptorProto: - msg.Options = removeDynamicExtensionsFromOptions(msg.Options) - case *descriptorpb.OneofDescriptorProto: - msg.Options = removeDynamicExtensionsFromOptions(msg.Options) - case *descriptorpb.EnumDescriptorProto: - msg.Options = removeDynamicExtensionsFromOptions(msg.Options) - case *descriptorpb.EnumValueDescriptorProto: - msg.Options = removeDynamicExtensionsFromOptions(msg.Options) - case *descriptorpb.ServiceDescriptorProto: - msg.Options = removeDynamicExtensionsFromOptions(msg.Options) - case *descriptorpb.MethodDescriptorProto: - msg.Options = removeDynamicExtensionsFromOptions(msg.Options) - } - return nil - }) -} - -type ptrMsg[T any] interface { - *T - proto.Message -} - -type fieldValue struct { - fd protoreflect.FieldDescriptor - val protoreflect.Value -} - -func removeDynamicExtensionsFromOptions[O ptrMsg[T], T any](opts O) O { - if opts == nil { - return nil - } - var dynamicExtensions []fieldValue - opts.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, val protoreflect.Value) bool { - if fd.IsExtension() { - dynamicExtensions = append(dynamicExtensions, fieldValue{fd: fd, val: val}) - } - return true - }) - - // serialize only these custom options - optsWithOnlyDyn := opts.ProtoReflect().Type().New() - for _, fv := range dynamicExtensions { - optsWithOnlyDyn.Set(fv.fd, fv.val) - } - data, err := proto.MarshalOptions{AllowPartial: true}.Marshal(optsWithOnlyDyn.Interface()) - if err != nil { - // oh, well... can't fix this one - return opts - } - - // and then replace values by clearing these custom options and deserializing - optsClone := proto.Clone(opts).ProtoReflect() - for _, fv := range dynamicExtensions { - optsClone.Clear(fv.fd) - } - err = proto.UnmarshalOptions{AllowPartial: true, Merge: true}.Unmarshal(data, optsClone.Interface()) - if err != nil { - // bummer, can't fix this one - return opts - } - - return optsClone.Interface().(O) -} diff --git a/vendor/github.com/jhump/protoreflect/desc/protoparse/resolve_files.go b/vendor/github.com/jhump/protoreflect/desc/protoparse/resolve_files.go deleted file mode 100644 index 3ae1415ab..000000000 --- a/vendor/github.com/jhump/protoreflect/desc/protoparse/resolve_files.go +++ /dev/null @@ -1,175 +0,0 @@ -package protoparse - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "strings" -) - -var errNoImportPathsForAbsoluteFilePath = errors.New("must specify at least one import path if any absolute file paths are given") - -// ResolveFilenames tries to resolve fileNames into paths that are relative to -// directories in the given importPaths. The returned slice has the results in -// the same order as they are supplied in fileNames. -// -// The resulting names should be suitable for passing to Parser.ParseFiles. -// -// If no import paths are given and any file name is absolute, this returns an -// error. If no import paths are given and all file names are relative, this -// returns the original file names. If a file name is already relative to one -// of the given import paths, it will be unchanged in the returned slice. If a -// file name given is relative to the current working directory, it will be made -// relative to one of the given import paths; but if it cannot be made relative -// (due to no matching import path), an error will be returned. -func ResolveFilenames(importPaths []string, fileNames ...string) ([]string, error) { - if len(importPaths) == 0 { - if containsAbsFilePath(fileNames) { - // We have to do this as otherwise parseProtoFiles can result in duplicate symbols. - // For example, assume we import "foo/bar/bar.proto" in a file "/home/alice/dev/foo/bar/baz.proto" - // as we call ParseFiles("/home/alice/dev/foo/bar/bar.proto","/home/alice/dev/foo/bar/baz.proto") - // with "/home/alice/dev" as our current directory. Due to the recursive nature of parseProtoFiles, - // it will discover the import "foo/bar/bar.proto" in the input file, and call parse on this, - // adding "foo/bar/bar.proto" to the parsed results, as well as "/home/alice/dev/foo/bar/bar.proto" - // from the input file list. This will result in a - // 'duplicate symbol SYMBOL: already defined as field in "/home/alice/dev/foo/bar/bar.proto' - // error being returned from ParseFiles. - return nil, errNoImportPathsForAbsoluteFilePath - } - return fileNames, nil - } - absImportPaths, err := absoluteFilePaths(importPaths) - if err != nil { - return nil, err - } - resolvedFileNames := make([]string, 0, len(fileNames)) - for _, fileName := range fileNames { - resolvedFileName, err := resolveFilename(absImportPaths, fileName) - if err != nil { - return nil, err - } - // On Windows, the resolved paths will use "\", but proto imports - // require the use of "/". So fix up here. - if filepath.Separator != '/' { - resolvedFileName = strings.Replace(resolvedFileName, string(filepath.Separator), "/", -1) - } - resolvedFileNames = append(resolvedFileNames, resolvedFileName) - } - return resolvedFileNames, nil -} - -func containsAbsFilePath(filePaths []string) bool { - for _, filePath := range filePaths { - if filepath.IsAbs(filePath) { - return true - } - } - return false -} - -func absoluteFilePaths(filePaths []string) ([]string, error) { - absFilePaths := make([]string, 0, len(filePaths)) - for _, filePath := range filePaths { - absFilePath, err := canonicalize(filePath) - if err != nil { - return nil, err - } - absFilePaths = append(absFilePaths, absFilePath) - } - return absFilePaths, nil -} - -func canonicalize(filePath string) (string, error) { - absPath, err := filepath.Abs(filePath) - if err != nil { - return "", err - } - // this is kind of gross, but it lets us construct a resolved path even if some - // path elements do not exist (a single call to filepath.EvalSymlinks would just - // return an error, ENOENT, in that case). - head := absPath - tail := "" - for { - noLinks, err := filepath.EvalSymlinks(head) - if err == nil { - if tail != "" { - return filepath.Join(noLinks, tail), nil - } - return noLinks, nil - } - - if tail == "" { - tail = filepath.Base(head) - } else { - tail = filepath.Join(filepath.Base(head), tail) - } - head = filepath.Dir(head) - if head == "." { - // ran out of path elements to try to resolve - return absPath, nil - } - } -} - -const dotPrefix = "." + string(filepath.Separator) -const dotDotPrefix = ".." + string(filepath.Separator) - -func resolveFilename(absImportPaths []string, fileName string) (string, error) { - if filepath.IsAbs(fileName) { - return resolveAbsFilename(absImportPaths, fileName) - } - - if !strings.HasPrefix(fileName, dotPrefix) && !strings.HasPrefix(fileName, dotDotPrefix) { - // Use of . and .. are assumed to be relative to current working - // directory. So if those aren't present, check to see if the file is - // relative to an import path. - for _, absImportPath := range absImportPaths { - absFileName := filepath.Join(absImportPath, fileName) - _, err := os.Stat(absFileName) - if err != nil { - continue - } - // found it! it was relative to this import path - return fileName, nil - } - } - - // must be relative to current working dir - return resolveAbsFilename(absImportPaths, fileName) -} - -func resolveAbsFilename(absImportPaths []string, fileName string) (string, error) { - absFileName, err := canonicalize(fileName) - if err != nil { - return "", err - } - for _, absImportPath := range absImportPaths { - if isDescendant(absImportPath, absFileName) { - resolvedPath, err := filepath.Rel(absImportPath, absFileName) - if err != nil { - return "", err - } - return resolvedPath, nil - } - } - return "", fmt.Errorf("%s does not reside in any import path", fileName) -} - -// isDescendant returns true if file is a descendant of dir. Both dir and file must -// be cleaned, absolute paths. -func isDescendant(dir, file string) bool { - dir = filepath.Clean(dir) - cur := file - for { - d := filepath.Dir(cur) - if d == dir { - return true - } - if d == "." || d == cur { - // we've run out of path elements - return false - } - cur = d - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt index ec26c0e06..3a12faaea 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -233,8 +233,6 @@ github.com/influxdata/influxdb1-client/v2 ## explicit; go 1.21 github.com/jhump/protoreflect/desc github.com/jhump/protoreflect/desc/internal -github.com/jhump/protoreflect/desc/protoparse -github.com/jhump/protoreflect/desc/protoparse/ast github.com/jhump/protoreflect/desc/sourceinfo github.com/jhump/protoreflect/grpcreflect github.com/jhump/protoreflect/internal