2018-08-15 11:24:18 -07:00
|
|
|
// Copyright 2018 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
// Package protogen provides support for writing protoc plugins.
|
|
|
|
//
|
2020-02-14 12:40:48 -08:00
|
|
|
// Plugins for protoc, the Protocol Buffer compiler,
|
|
|
|
// are programs which read a CodeGeneratorRequest message from standard input
|
|
|
|
// and write a CodeGeneratorResponse message to standard output.
|
|
|
|
// This package provides support for writing plugins which generate Go code.
|
2018-08-15 11:24:18 -07:00
|
|
|
package protogen
|
|
|
|
|
|
|
|
import (
|
2018-08-22 13:46:02 -07:00
|
|
|
"bufio"
|
2018-08-15 11:24:18 -07:00
|
|
|
"bytes"
|
2018-10-17 12:53:18 -07:00
|
|
|
"encoding/binary"
|
2018-08-15 11:24:18 -07:00
|
|
|
"fmt"
|
2018-09-13 13:12:36 -07:00
|
|
|
"go/ast"
|
2018-08-22 13:46:02 -07:00
|
|
|
"go/parser"
|
|
|
|
"go/printer"
|
|
|
|
"go/token"
|
2019-01-14 11:48:43 -08:00
|
|
|
"go/types"
|
2018-08-15 11:24:18 -07:00
|
|
|
"io/ioutil"
|
2019-09-07 13:06:27 -07:00
|
|
|
"log"
|
2018-08-15 11:24:18 -07:00
|
|
|
"os"
|
2018-09-06 10:23:53 -07:00
|
|
|
"path"
|
2018-08-15 11:24:18 -07:00
|
|
|
"path/filepath"
|
2018-08-23 14:39:30 -07:00
|
|
|
"sort"
|
|
|
|
"strconv"
|
2018-08-15 11:24:18 -07:00
|
|
|
"strings"
|
|
|
|
|
2019-05-14 12:44:37 -07:00
|
|
|
"google.golang.org/protobuf/encoding/prototext"
|
2019-05-13 23:55:40 -07:00
|
|
|
"google.golang.org/protobuf/internal/fieldnum"
|
2019-08-23 12:18:57 -07:00
|
|
|
"google.golang.org/protobuf/internal/strs"
|
2019-05-13 23:55:40 -07:00
|
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
"google.golang.org/protobuf/reflect/protodesc"
|
|
|
|
"google.golang.org/protobuf/reflect/protoreflect"
|
|
|
|
"google.golang.org/protobuf/reflect/protoregistry"
|
2018-11-26 18:55:29 -08:00
|
|
|
|
2019-05-16 12:47:20 -07:00
|
|
|
"google.golang.org/protobuf/types/descriptorpb"
|
|
|
|
"google.golang.org/protobuf/types/pluginpb"
|
2018-08-15 11:24:18 -07:00
|
|
|
)
|
|
|
|
|
2020-02-24 11:21:30 -08:00
|
|
|
const goPackageDocURL = "https://developers.google.com/protocol-buffers/docs/reference/go-generated#package"
|
|
|
|
|
2018-08-15 11:24:18 -07:00
|
|
|
// Run executes a function as a protoc plugin.
|
|
|
|
//
|
|
|
|
// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
|
|
|
|
// function, and writes a CodeGeneratorResponse message to os.Stdout.
|
|
|
|
//
|
|
|
|
// If a failure occurs while reading or writing, Run prints an error to
|
|
|
|
// os.Stderr and calls os.Exit(1).
|
2020-02-27 14:47:29 -08:00
|
|
|
func (opts Options) Run(f func(*Plugin) error) {
|
2018-09-11 13:53:14 -07:00
|
|
|
if err := run(opts, f); err != nil {
|
2018-08-15 11:24:18 -07:00
|
|
|
fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-27 14:47:29 -08:00
|
|
|
func run(opts Options, f func(*Plugin) error) error {
|
2018-10-04 15:30:51 -07:00
|
|
|
if len(os.Args) > 1 {
|
|
|
|
return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
in, err := ioutil.ReadAll(os.Stdin)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
req := &pluginpb.CodeGeneratorRequest{}
|
|
|
|
if err := proto.Unmarshal(in, req); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-02-27 14:47:29 -08:00
|
|
|
gen, err := opts.New(req)
|
2018-08-15 11:24:18 -07:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := f(gen); err != nil {
|
|
|
|
// Errors from the plugin function are reported by setting the
|
|
|
|
// error field in the CodeGeneratorResponse.
|
|
|
|
//
|
|
|
|
// In contrast, errors that indicate a problem in protoc
|
|
|
|
// itself (unparsable input, I/O errors, etc.) are reported
|
|
|
|
// to stderr.
|
|
|
|
gen.Error(err)
|
|
|
|
}
|
|
|
|
resp := gen.Response()
|
|
|
|
out, err := proto.Marshal(resp)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if _, err := os.Stdout.Write(out); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// A Plugin is a protoc plugin invocation.
|
|
|
|
type Plugin struct {
|
|
|
|
// Request is the CodeGeneratorRequest provided by protoc.
|
|
|
|
Request *pluginpb.CodeGeneratorRequest
|
|
|
|
|
|
|
|
// Files is the set of files to generate and everything they import.
|
|
|
|
// Files appear in topological order, so each file appears before any
|
|
|
|
// file that imports it.
|
|
|
|
Files []*File
|
2019-08-20 20:14:19 -07:00
|
|
|
FilesByPath map[string]*File
|
2018-08-15 11:24:18 -07:00
|
|
|
|
2020-04-28 14:44:38 -07:00
|
|
|
// SupportedFeatures is the set of protobuf language features supported by
|
|
|
|
// this generator plugin. See the documentation for
|
|
|
|
// google.protobuf.CodeGeneratorResponse.supported_features for details.
|
|
|
|
SupportedFeatures uint64
|
|
|
|
|
2018-09-10 12:26:21 -07:00
|
|
|
fileReg *protoregistry.Files
|
|
|
|
enumsByName map[protoreflect.FullName]*Enum
|
2019-08-20 20:10:23 -07:00
|
|
|
messagesByName map[protoreflect.FullName]*Message
|
2018-10-04 12:42:37 -07:00
|
|
|
annotateCode bool
|
2018-09-10 12:26:21 -07:00
|
|
|
pathType pathType
|
2020-02-12 23:38:30 -08:00
|
|
|
module string
|
2018-09-10 12:26:21 -07:00
|
|
|
genFiles []*GeneratedFile
|
2020-02-27 14:47:29 -08:00
|
|
|
opts Options
|
2018-09-10 12:26:21 -07:00
|
|
|
err error
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
|
|
|
|
2018-09-11 13:53:14 -07:00
|
|
|
type Options struct {
|
|
|
|
// If ParamFunc is non-nil, it will be called with each unknown
|
|
|
|
// generator parameter.
|
|
|
|
//
|
|
|
|
// Plugins for protoc can accept parameters from the command line,
|
|
|
|
// passed in the --<lang>_out protoc, separated from the output
|
|
|
|
// directory with a colon; e.g.,
|
|
|
|
//
|
|
|
|
// --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
|
|
|
|
//
|
|
|
|
// Parameters passed in this fashion as a comma-separated list of
|
|
|
|
// key=value pairs will be passed to the ParamFunc.
|
|
|
|
//
|
|
|
|
// The (flag.FlagSet).Set method matches this function signature,
|
|
|
|
// so parameters can be converted into flags as in the following:
|
|
|
|
//
|
|
|
|
// var flags flag.FlagSet
|
|
|
|
// value := flags.Bool("param", false, "")
|
|
|
|
// opts := &protogen.Options{
|
|
|
|
// ParamFunc: flags.Set,
|
|
|
|
// }
|
|
|
|
// protogen.Run(opts, func(p *protogen.Plugin) error {
|
|
|
|
// if *value { ... }
|
|
|
|
// })
|
|
|
|
ParamFunc func(name, value string) error
|
2018-09-27 15:51:05 -07:00
|
|
|
|
|
|
|
// ImportRewriteFunc is called with the import path of each package
|
|
|
|
// imported by a generated file. It returns the import path to use
|
|
|
|
// for this package.
|
|
|
|
ImportRewriteFunc func(GoImportPath) GoImportPath
|
2018-09-11 13:53:14 -07:00
|
|
|
}
|
|
|
|
|
2018-08-15 11:24:18 -07:00
|
|
|
// New returns a new Plugin.
|
2020-02-27 14:47:29 -08:00
|
|
|
func (opts Options) New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) {
|
2018-08-15 11:24:18 -07:00
|
|
|
gen := &Plugin{
|
2018-09-10 12:26:21 -07:00
|
|
|
Request: req,
|
2019-08-20 20:14:19 -07:00
|
|
|
FilesByPath: make(map[string]*File),
|
2019-10-08 13:28:53 -07:00
|
|
|
fileReg: new(protoregistry.Files),
|
2018-09-10 12:26:21 -07:00
|
|
|
enumsByName: make(map[protoreflect.FullName]*Enum),
|
2019-08-20 20:10:23 -07:00
|
|
|
messagesByName: make(map[protoreflect.FullName]*Message),
|
2018-09-27 15:51:05 -07:00
|
|
|
opts: opts,
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
|
|
|
|
2018-09-06 10:23:53 -07:00
|
|
|
packageNames := make(map[string]GoPackageName) // filename -> package name
|
|
|
|
importPaths := make(map[string]GoImportPath) // filename -> import path
|
2019-09-07 13:06:27 -07:00
|
|
|
mfiles := make(map[string]bool) // filename set
|
2018-09-06 10:23:53 -07:00
|
|
|
var packageImportPath GoImportPath
|
2018-08-15 11:24:18 -07:00
|
|
|
for _, param := range strings.Split(req.GetParameter(), ",") {
|
|
|
|
var value string
|
|
|
|
if i := strings.Index(param, "="); i >= 0 {
|
|
|
|
value = param[i+1:]
|
|
|
|
param = param[0:i]
|
|
|
|
}
|
|
|
|
switch param {
|
|
|
|
case "":
|
|
|
|
// Ignore.
|
|
|
|
case "import_path":
|
2018-09-06 10:23:53 -07:00
|
|
|
packageImportPath = GoImportPath(value)
|
2020-02-12 23:38:30 -08:00
|
|
|
case "module":
|
|
|
|
gen.module = value
|
2018-08-15 11:24:18 -07:00
|
|
|
case "paths":
|
2018-09-06 10:23:53 -07:00
|
|
|
switch value {
|
|
|
|
case "import":
|
|
|
|
gen.pathType = pathTypeImport
|
|
|
|
case "source_relative":
|
|
|
|
gen.pathType = pathTypeSourceRelative
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
case "annotate_code":
|
2018-10-04 12:42:37 -07:00
|
|
|
switch value {
|
|
|
|
case "true", "":
|
|
|
|
gen.annotateCode = true
|
|
|
|
case "false":
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
default:
|
2018-09-11 13:53:14 -07:00
|
|
|
if param[0] == 'M' {
|
2020-03-18 00:59:09 -07:00
|
|
|
if i := strings.Index(value, ";"); i >= 0 {
|
|
|
|
pkgName := GoPackageName(value[i+1:])
|
|
|
|
if otherName, ok := packageNames[param[1:]]; ok && pkgName != otherName {
|
|
|
|
return nil, fmt.Errorf("inconsistent package names for %q: %q != %q", value[:i], pkgName, otherName)
|
|
|
|
}
|
|
|
|
packageNames[param[1:]] = pkgName
|
|
|
|
value = value[:i]
|
|
|
|
}
|
2018-09-11 13:53:14 -07:00
|
|
|
importPaths[param[1:]] = GoImportPath(value)
|
2019-09-07 13:06:27 -07:00
|
|
|
mfiles[param[1:]] = true
|
2018-09-11 13:53:14 -07:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
if opts.ParamFunc != nil {
|
|
|
|
if err := opts.ParamFunc(param, value); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-02-12 23:38:30 -08:00
|
|
|
if gen.module != "" {
|
|
|
|
// When the module= option is provided, we strip the module name
|
|
|
|
// prefix from generated files. This only makes sense if generated
|
|
|
|
// filenames are based on the import path, so default to paths=import
|
|
|
|
// and complain if source_relative was selected manually.
|
|
|
|
switch gen.pathType {
|
|
|
|
case pathTypeLegacy:
|
|
|
|
gen.pathType = pathTypeImport
|
|
|
|
case pathTypeSourceRelative:
|
|
|
|
return nil, fmt.Errorf("cannot use module= with paths=source_relative")
|
|
|
|
}
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
|
2018-09-06 10:23:53 -07:00
|
|
|
// Figure out the import path and package name for each file.
|
|
|
|
//
|
|
|
|
// The rules here are complicated and have grown organically over time.
|
|
|
|
// Interactions between different ways of specifying package information
|
|
|
|
// may be surprising.
|
|
|
|
//
|
|
|
|
// The recommended approach is to include a go_package option in every
|
|
|
|
// .proto source file specifying the full import path of the Go package
|
|
|
|
// associated with this file.
|
|
|
|
//
|
2019-05-16 15:53:25 -07:00
|
|
|
// option go_package = "google.golang.org/protobuf/types/known/anypb";
|
2018-09-06 10:23:53 -07:00
|
|
|
//
|
|
|
|
// Build systems which want to exert full control over import paths may
|
|
|
|
// specify M<filename>=<import_path> flags.
|
|
|
|
//
|
|
|
|
// Other approaches are not recommend.
|
|
|
|
generatedFileNames := make(map[string]bool)
|
|
|
|
for _, name := range gen.Request.FileToGenerate {
|
|
|
|
generatedFileNames[name] = true
|
|
|
|
}
|
|
|
|
// We need to determine the import paths before the package names,
|
|
|
|
// because the Go package name for a file is sometimes derived from
|
|
|
|
// different file in the same package.
|
|
|
|
packageNameForImportPath := make(map[GoImportPath]GoPackageName)
|
|
|
|
for _, fdesc := range gen.Request.ProtoFile {
|
|
|
|
filename := fdesc.GetName()
|
|
|
|
packageName, importPath := goPackageOption(fdesc)
|
|
|
|
switch {
|
|
|
|
case importPaths[filename] != "":
|
2020-02-15 14:28:51 -08:00
|
|
|
// Command line: Mfoo.proto=quux/bar
|
2018-09-06 10:23:53 -07:00
|
|
|
//
|
|
|
|
// Explicit mapping of source file to import path.
|
|
|
|
case generatedFileNames[filename] && packageImportPath != "":
|
|
|
|
// Command line: import_path=quux/bar
|
|
|
|
//
|
|
|
|
// The import_path flag sets the import path for every file that
|
|
|
|
// we generate code for.
|
|
|
|
importPaths[filename] = packageImportPath
|
|
|
|
case importPath != "":
|
|
|
|
// Source file: option go_package = "quux/bar";
|
|
|
|
//
|
|
|
|
// The go_package option sets the import path. Most users should use this.
|
|
|
|
importPaths[filename] = importPath
|
|
|
|
default:
|
|
|
|
// Source filename.
|
|
|
|
//
|
|
|
|
// Last resort when nothing else is available.
|
|
|
|
importPaths[filename] = GoImportPath(path.Dir(filename))
|
|
|
|
}
|
|
|
|
if packageName != "" {
|
|
|
|
packageNameForImportPath[importPaths[filename]] = packageName
|
|
|
|
}
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
for _, fdesc := range gen.Request.ProtoFile {
|
2018-09-06 10:23:53 -07:00
|
|
|
filename := fdesc.GetName()
|
2019-09-07 13:06:27 -07:00
|
|
|
packageName, importPath := goPackageOption(fdesc)
|
2018-09-06 10:23:53 -07:00
|
|
|
defaultPackageName := packageNameForImportPath[importPaths[filename]]
|
|
|
|
switch {
|
2020-03-18 00:59:09 -07:00
|
|
|
case packageNames[filename] != "":
|
|
|
|
// A package name specified by the "M" command-line argument.
|
2018-09-06 10:23:53 -07:00
|
|
|
case packageName != "":
|
2019-09-07 13:06:27 -07:00
|
|
|
// TODO: For the "M" command-line argument, this means that the
|
|
|
|
// package name can be derived from the go_package option.
|
|
|
|
// Go package information should either consistently come from the
|
|
|
|
// command-line or the .proto source file, but not both.
|
|
|
|
// See how to make this consistent.
|
|
|
|
|
2018-09-06 10:23:53 -07:00
|
|
|
// Source file: option go_package = "quux/bar";
|
|
|
|
packageNames[filename] = packageName
|
|
|
|
case defaultPackageName != "":
|
|
|
|
// A go_package option in another file in the same package.
|
|
|
|
//
|
|
|
|
// This is a poor choice in general, since every source file should
|
|
|
|
// contain a go_package option. Supported mainly for historical
|
|
|
|
// compatibility.
|
|
|
|
packageNames[filename] = defaultPackageName
|
|
|
|
case generatedFileNames[filename] && packageImportPath != "":
|
|
|
|
// Command line: import_path=quux/bar
|
|
|
|
packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
|
|
|
|
case fdesc.GetPackage() != "":
|
|
|
|
// Source file: package quux.bar;
|
|
|
|
packageNames[filename] = cleanPackageName(fdesc.GetPackage())
|
|
|
|
default:
|
|
|
|
// Source filename.
|
|
|
|
packageNames[filename] = cleanPackageName(baseName(filename))
|
|
|
|
}
|
2019-09-07 13:06:27 -07:00
|
|
|
|
|
|
|
goPkgOpt := string(importPaths[filename])
|
|
|
|
if path.Base(string(goPkgOpt)) != string(packageNames[filename]) {
|
|
|
|
goPkgOpt += ";" + string(packageNames[filename])
|
|
|
|
}
|
|
|
|
switch {
|
|
|
|
case packageImportPath != "":
|
|
|
|
// Command line: import_path=quux/bar
|
2020-03-06 13:58:41 -08:00
|
|
|
warn("Deprecated use of the 'import_path' command-line argument. In %q, please specify:\n"+
|
2019-09-07 13:06:27 -07:00
|
|
|
"\toption go_package = %q;\n"+
|
|
|
|
"A future release of protoc-gen-go will no longer support the 'import_path' argument.\n"+
|
2020-02-24 11:21:30 -08:00
|
|
|
"See "+goPackageDocURL+" for more information.\n"+
|
2019-09-07 13:06:27 -07:00
|
|
|
"\n", fdesc.GetName(), goPkgOpt)
|
|
|
|
case mfiles[filename]:
|
|
|
|
// Command line: M=foo.proto=quux/bar
|
|
|
|
case packageName != "" && importPath == "":
|
|
|
|
// Source file: option go_package = "quux";
|
2020-03-06 13:58:41 -08:00
|
|
|
warn("Deprecated use of 'go_package' option without a full import path in %q, please specify:\n"+
|
2019-09-07 13:06:27 -07:00
|
|
|
"\toption go_package = %q;\n"+
|
|
|
|
"A future release of protoc-gen-go will require the import path be specified.\n"+
|
2020-02-24 11:21:30 -08:00
|
|
|
"See "+goPackageDocURL+" for more information.\n"+
|
2019-09-07 13:06:27 -07:00
|
|
|
"\n", fdesc.GetName(), goPkgOpt)
|
|
|
|
case packageName == "" && importPath == "":
|
|
|
|
// No Go package information provided.
|
2020-05-05 12:01:13 -07:00
|
|
|
dotIdx := strings.Index(goPkgOpt, ".") // heuristic for top-level domain
|
|
|
|
slashIdx := strings.Index(goPkgOpt, "/") // heuristic for multi-segment path
|
|
|
|
if isFull := 0 <= dotIdx && dotIdx <= slashIdx; isFull {
|
|
|
|
warn("Missing 'go_package' option in %q, please specify:\n"+
|
|
|
|
"\toption go_package = %q;\n"+
|
|
|
|
"A future release of protoc-gen-go will require this be specified.\n"+
|
|
|
|
"See "+goPackageDocURL+" for more information.\n"+
|
|
|
|
"\n", fdesc.GetName(), goPkgOpt)
|
|
|
|
} else {
|
|
|
|
warn("Missing 'go_package' option in %q,\n"+
|
|
|
|
"please specify it with the full Go package path as\n"+
|
|
|
|
"a future release of protoc-gen-go will require this be specified.\n"+
|
|
|
|
"See "+goPackageDocURL+" for more information.\n"+
|
|
|
|
"\n", fdesc.GetName())
|
|
|
|
}
|
2019-09-07 13:06:27 -07:00
|
|
|
}
|
2018-09-06 10:23:53 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Consistency check: Every file with the same Go import path should have
|
|
|
|
// the same Go package name.
|
|
|
|
packageFiles := make(map[GoImportPath][]string)
|
|
|
|
for filename, importPath := range importPaths {
|
2018-10-08 16:36:49 -07:00
|
|
|
if _, ok := packageNames[filename]; !ok {
|
|
|
|
// Skip files mentioned in a M<file>=<import_path> parameter
|
|
|
|
// but which do not appear in the CodeGeneratorRequest.
|
|
|
|
continue
|
|
|
|
}
|
2018-09-06 10:23:53 -07:00
|
|
|
packageFiles[importPath] = append(packageFiles[importPath], filename)
|
|
|
|
}
|
|
|
|
for importPath, filenames := range packageFiles {
|
|
|
|
for i := 1; i < len(filenames); i++ {
|
|
|
|
if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
|
|
|
|
return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
|
|
|
|
importPath, a, filenames[0], b, filenames[i])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, fdesc := range gen.Request.ProtoFile {
|
|
|
|
filename := fdesc.GetName()
|
2019-08-20 20:14:19 -07:00
|
|
|
if gen.FilesByPath[filename] != nil {
|
2018-09-06 10:23:53 -07:00
|
|
|
return nil, fmt.Errorf("duplicate file name: %q", filename)
|
|
|
|
}
|
|
|
|
f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
|
2018-08-23 14:39:30 -07:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
gen.Files = append(gen.Files, f)
|
2019-08-20 20:14:19 -07:00
|
|
|
gen.FilesByPath[filename] = f
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
2018-09-06 10:23:53 -07:00
|
|
|
for _, filename := range gen.Request.FileToGenerate {
|
2019-08-20 20:14:19 -07:00
|
|
|
f, ok := gen.FilesByPath[filename]
|
2018-08-15 11:24:18 -07:00
|
|
|
if !ok {
|
2018-09-06 10:23:53 -07:00
|
|
|
return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
|
|
|
f.Generate = true
|
|
|
|
}
|
|
|
|
return gen, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error records an error in code generation. The generator will report the
|
|
|
|
// error back to protoc and will not produce output.
|
|
|
|
func (gen *Plugin) Error(err error) {
|
|
|
|
if gen.err == nil {
|
|
|
|
gen.err = err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Response returns the generator output.
|
|
|
|
func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
|
|
|
|
resp := &pluginpb.CodeGeneratorResponse{}
|
|
|
|
if gen.err != nil {
|
2019-07-10 16:17:16 -07:00
|
|
|
resp.Error = proto.String(gen.err.Error())
|
2018-08-15 11:24:18 -07:00
|
|
|
return resp
|
|
|
|
}
|
2018-10-04 12:42:37 -07:00
|
|
|
for _, g := range gen.genFiles {
|
2018-12-21 15:54:06 -08:00
|
|
|
if g.skip {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
content, err := g.Content()
|
2018-08-22 13:46:02 -07:00
|
|
|
if err != nil {
|
|
|
|
return &pluginpb.CodeGeneratorResponse{
|
2019-07-10 16:17:16 -07:00
|
|
|
Error: proto.String(err.Error()),
|
2018-08-22 13:46:02 -07:00
|
|
|
}
|
|
|
|
}
|
2020-02-12 23:38:30 -08:00
|
|
|
filename := g.filename
|
|
|
|
if gen.module != "" {
|
|
|
|
trim := gen.module + "/"
|
|
|
|
if !strings.HasPrefix(filename, trim) {
|
|
|
|
return &pluginpb.CodeGeneratorResponse{
|
|
|
|
Error: proto.String(fmt.Sprintf("%v: generated file does not match prefix %q", filename, gen.module)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
filename = strings.TrimPrefix(filename, trim)
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
|
2020-02-12 23:38:30 -08:00
|
|
|
Name: proto.String(filename),
|
2019-07-10 16:17:16 -07:00
|
|
|
Content: proto.String(string(content)),
|
2018-08-15 11:24:18 -07:00
|
|
|
})
|
2018-10-04 12:42:37 -07:00
|
|
|
if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
|
|
|
|
meta, err := g.metaFile(content)
|
|
|
|
if err != nil {
|
|
|
|
return &pluginpb.CodeGeneratorResponse{
|
2019-07-10 16:17:16 -07:00
|
|
|
Error: proto.String(err.Error()),
|
2018-10-04 12:42:37 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
|
2020-02-12 23:38:30 -08:00
|
|
|
Name: proto.String(filename + ".meta"),
|
2019-07-10 16:17:16 -07:00
|
|
|
Content: proto.String(meta),
|
2018-10-04 12:42:37 -07:00
|
|
|
})
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
2020-04-28 14:44:38 -07:00
|
|
|
if gen.SupportedFeatures > 0 {
|
|
|
|
resp.SupportedFeatures = proto.Uint64(gen.SupportedFeatures)
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
return resp
|
|
|
|
}
|
|
|
|
|
2018-08-22 13:46:02 -07:00
|
|
|
// A File describes a .proto source file.
|
2018-08-15 11:24:18 -07:00
|
|
|
type File struct {
|
2018-09-07 14:14:06 -07:00
|
|
|
Desc protoreflect.FileDescriptor
|
2018-11-26 18:55:29 -08:00
|
|
|
Proto *descriptorpb.FileDescriptorProto
|
2018-08-15 11:24:18 -07:00
|
|
|
|
cmd/protoc-gen-go: add support for protobuf reflection
Implement support in protoc-gen-go for generating messages and enums
that satisfy the v2 protobuf reflection interfaces. Specifically, the following
are added:
* top-level variable representing the file descriptor
* ProtoReflect method on enums (to implement protoV2.Enum)
* ProtoReflect method on messages (to implement protoV2.Message)
The following are not supported yet:
* resolving transitive dependencies for file imports
* Extension descriptors
* Service descriptors
The implementation approach creates a single array for all the message and enum
declarations and references sections of that array to complete dependencies.
Since protobuf declarations can form a graph (a message may depend on itself),
it is difficult to construct a graph as a single literal. One way is to use
placeholder descriptors, but that is not efficient as it requires encoding
the full name of each dependent enum and message and then later resolving it;
thus, both expanding the binary size and also increasing initialization cost.
Instead, we add a prototype.{Enum,Message}.Reference method to obtain a
descriptor reference for the purposes for satisfying dependencies.
As such, nested declarations and dependencies are populated in an init function.
Other changes to support the implementation:
* Added a protoimpl package to expose the MessageType type and also the
MessageTypeOf and EnumTypeOf helper functions.
* Added a protogen.File.GoIdent field to provide a suggested variable name
for the file descriptor.
* Added prototype.{Enum,Message}.Reference that provides a descriptor reference
for the purposes for satisfying cyclic dependencies.
* Added protoreflect.{Syntax,Cardinality,Kind}.GoString to obtain a Go source
identifier that represents the given constant.
Change-Id: I9455764882dee6ad10f251901e7d419091e8bf1d
Reviewed-on: https://go-review.googlesource.com/c/150074
Reviewed-by: Damien Neil <dneil@google.com>
2018-11-15 14:44:37 -08:00
|
|
|
GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
|
|
|
|
GoPackageName GoPackageName // name of this file's Go package
|
|
|
|
GoImportPath GoImportPath // import path of this file's Go package
|
2019-08-20 20:10:23 -07:00
|
|
|
|
|
|
|
Enums []*Enum // top-level enum declarations
|
|
|
|
Messages []*Message // top-level message declarations
|
|
|
|
Extensions []*Extension // top-level extension declarations
|
|
|
|
Services []*Service // top-level service declarations
|
|
|
|
|
|
|
|
Generate bool // true if we should generate code for this file
|
2018-09-06 10:23:53 -07:00
|
|
|
|
|
|
|
// GeneratedFilenamePrefix is used to construct filenames for generated
|
|
|
|
// files associated with this source file.
|
|
|
|
//
|
|
|
|
// For example, the source file "dir/foo.proto" might have a filename prefix
|
|
|
|
// of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
|
|
|
|
GeneratedFilenamePrefix string
|
2018-10-17 12:53:18 -07:00
|
|
|
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
comments map[pathKey]CommentSet
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
|
|
|
|
2018-11-26 18:55:29 -08:00
|
|
|
func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
|
|
|
|
desc, err := protodesc.NewFile(p, gen.fileReg)
|
2018-08-23 14:39:30 -07:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
|
|
|
|
}
|
2019-10-08 13:28:53 -07:00
|
|
|
if err := gen.fileReg.RegisterFile(desc); err != nil {
|
2018-08-23 14:39:30 -07:00
|
|
|
return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
|
|
|
|
}
|
2018-08-22 13:46:02 -07:00
|
|
|
f := &File{
|
2018-09-06 10:23:53 -07:00
|
|
|
Desc: desc,
|
2018-09-07 14:14:06 -07:00
|
|
|
Proto: p,
|
2018-09-06 10:23:53 -07:00
|
|
|
GoPackageName: packageName,
|
|
|
|
GoImportPath: importPath,
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
comments: make(map[pathKey]CommentSet),
|
2018-09-06 10:23:53 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Determine the prefix for generated Go files.
|
|
|
|
prefix := p.GetName()
|
|
|
|
if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
|
|
|
|
prefix = prefix[:len(prefix)-len(ext)]
|
|
|
|
}
|
2020-02-15 14:28:51 -08:00
|
|
|
switch gen.pathType {
|
|
|
|
case pathTypeLegacy:
|
|
|
|
// The default is to derive the output filename from the Go import path
|
|
|
|
// if the file contains a go_package option,or from the input filename instead.
|
2018-09-06 10:23:53 -07:00
|
|
|
if _, importPath := goPackageOption(p); importPath != "" {
|
|
|
|
prefix = path.Join(string(importPath), path.Base(prefix))
|
|
|
|
}
|
2020-02-15 14:28:51 -08:00
|
|
|
case pathTypeImport:
|
|
|
|
// If paths=import, the output filename is derived from the Go import path.
|
|
|
|
prefix = path.Join(string(f.GoImportPath), path.Base(prefix))
|
|
|
|
case pathTypeSourceRelative:
|
|
|
|
// If paths=source_relative, the output filename is derived from
|
|
|
|
// the input filename.
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
cmd/protoc-gen-go: add support for protobuf reflection
Implement support in protoc-gen-go for generating messages and enums
that satisfy the v2 protobuf reflection interfaces. Specifically, the following
are added:
* top-level variable representing the file descriptor
* ProtoReflect method on enums (to implement protoV2.Enum)
* ProtoReflect method on messages (to implement protoV2.Message)
The following are not supported yet:
* resolving transitive dependencies for file imports
* Extension descriptors
* Service descriptors
The implementation approach creates a single array for all the message and enum
declarations and references sections of that array to complete dependencies.
Since protobuf declarations can form a graph (a message may depend on itself),
it is difficult to construct a graph as a single literal. One way is to use
placeholder descriptors, but that is not efficient as it requires encoding
the full name of each dependent enum and message and then later resolving it;
thus, both expanding the binary size and also increasing initialization cost.
Instead, we add a prototype.{Enum,Message}.Reference method to obtain a
descriptor reference for the purposes for satisfying dependencies.
As such, nested declarations and dependencies are populated in an init function.
Other changes to support the implementation:
* Added a protoimpl package to expose the MessageType type and also the
MessageTypeOf and EnumTypeOf helper functions.
* Added a protogen.File.GoIdent field to provide a suggested variable name
for the file descriptor.
* Added prototype.{Enum,Message}.Reference that provides a descriptor reference
for the purposes for satisfying cyclic dependencies.
* Added protoreflect.{Syntax,Cardinality,Kind}.GoString to obtain a Go source
identifier that represents the given constant.
Change-Id: I9455764882dee6ad10f251901e7d419091e8bf1d
Reviewed-on: https://go-review.googlesource.com/c/150074
Reviewed-by: Damien Neil <dneil@google.com>
2018-11-15 14:44:37 -08:00
|
|
|
f.GoDescriptorIdent = GoIdent{
|
2019-08-23 12:18:57 -07:00
|
|
|
GoName: "File_" + strs.GoSanitized(p.GetName()),
|
cmd/protoc-gen-go: add support for protobuf reflection
Implement support in protoc-gen-go for generating messages and enums
that satisfy the v2 protobuf reflection interfaces. Specifically, the following
are added:
* top-level variable representing the file descriptor
* ProtoReflect method on enums (to implement protoV2.Enum)
* ProtoReflect method on messages (to implement protoV2.Message)
The following are not supported yet:
* resolving transitive dependencies for file imports
* Extension descriptors
* Service descriptors
The implementation approach creates a single array for all the message and enum
declarations and references sections of that array to complete dependencies.
Since protobuf declarations can form a graph (a message may depend on itself),
it is difficult to construct a graph as a single literal. One way is to use
placeholder descriptors, but that is not efficient as it requires encoding
the full name of each dependent enum and message and then later resolving it;
thus, both expanding the binary size and also increasing initialization cost.
Instead, we add a prototype.{Enum,Message}.Reference method to obtain a
descriptor reference for the purposes for satisfying dependencies.
As such, nested declarations and dependencies are populated in an init function.
Other changes to support the implementation:
* Added a protoimpl package to expose the MessageType type and also the
MessageTypeOf and EnumTypeOf helper functions.
* Added a protogen.File.GoIdent field to provide a suggested variable name
for the file descriptor.
* Added prototype.{Enum,Message}.Reference that provides a descriptor reference
for the purposes for satisfying cyclic dependencies.
* Added protoreflect.{Syntax,Cardinality,Kind}.GoString to obtain a Go source
identifier that represents the given constant.
Change-Id: I9455764882dee6ad10f251901e7d419091e8bf1d
Reviewed-on: https://go-review.googlesource.com/c/150074
Reviewed-by: Damien Neil <dneil@google.com>
2018-11-15 14:44:37 -08:00
|
|
|
GoImportPath: f.GoImportPath,
|
|
|
|
}
|
2018-09-06 10:23:53 -07:00
|
|
|
f.GeneratedFilenamePrefix = prefix
|
|
|
|
|
2018-10-17 12:53:18 -07:00
|
|
|
for _, loc := range p.GetSourceCodeInfo().GetLocation() {
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
// Descriptors declarations are guaranteed to have unique comment sets.
|
|
|
|
// Other locations may not be unique, but we don't use them.
|
|
|
|
var leadingDetached []Comments
|
|
|
|
for _, s := range loc.GetLeadingDetachedComments() {
|
|
|
|
leadingDetached = append(leadingDetached, Comments(s))
|
|
|
|
}
|
|
|
|
f.comments[newPathKey(loc.Path)] = CommentSet{
|
|
|
|
LeadingDetached: leadingDetached,
|
|
|
|
Leading: Comments(loc.GetLeadingComments()),
|
|
|
|
Trailing: Comments(loc.GetTrailingComments()),
|
|
|
|
}
|
2018-10-17 12:53:18 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
|
|
|
|
f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
|
2018-08-22 13:46:02 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
|
|
|
|
f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
|
2018-09-07 12:45:37 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
|
|
|
|
f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
|
2018-09-14 15:41:11 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
|
|
|
|
f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
|
2018-09-21 15:03:34 -07:00
|
|
|
}
|
2018-09-13 15:07:10 -07:00
|
|
|
for _, message := range f.Messages {
|
2019-08-20 20:10:23 -07:00
|
|
|
if err := message.resolveDependencies(gen); err != nil {
|
2018-09-14 15:41:11 -07:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, extension := range f.Extensions {
|
2019-08-20 20:10:23 -07:00
|
|
|
if err := extension.resolveDependencies(gen); err != nil {
|
2018-09-14 15:41:11 -07:00
|
|
|
return nil, err
|
|
|
|
}
|
2018-09-13 15:07:10 -07:00
|
|
|
}
|
2018-09-21 15:03:34 -07:00
|
|
|
for _, service := range f.Services {
|
|
|
|
for _, method := range service.Methods {
|
2019-08-20 20:10:23 -07:00
|
|
|
if err := method.resolveDependencies(gen); err != nil {
|
2018-09-21 15:03:34 -07:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-08-23 14:39:30 -07:00
|
|
|
return f, nil
|
2018-08-22 13:46:02 -07:00
|
|
|
}
|
|
|
|
|
2019-05-24 18:24:29 +09:00
|
|
|
func (f *File) location(idxPath ...int32) Location {
|
2018-10-04 12:42:37 -07:00
|
|
|
return Location{
|
|
|
|
SourceFile: f.Desc.Path(),
|
2019-05-24 18:24:29 +09:00
|
|
|
Path: idxPath,
|
2018-10-04 12:42:37 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-06 10:23:53 -07:00
|
|
|
// goPackageOption interprets a file's go_package option.
|
|
|
|
// If there is no go_package, it returns ("", "").
|
|
|
|
// If there's a simple name, it returns (pkg, "").
|
|
|
|
// If the option implies an import path, it returns (pkg, impPath).
|
2018-11-26 18:55:29 -08:00
|
|
|
func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
|
2018-09-06 10:23:53 -07:00
|
|
|
opt := d.GetOptions().GetGoPackage()
|
|
|
|
if opt == "" {
|
|
|
|
return "", ""
|
|
|
|
}
|
2019-09-07 13:06:27 -07:00
|
|
|
rawPkg, impPath := goPackageOptionRaw(opt)
|
|
|
|
pkg = cleanPackageName(rawPkg)
|
|
|
|
if string(pkg) != rawPkg && impPath != "" {
|
2020-03-06 13:58:41 -08:00
|
|
|
warn("Malformed 'go_package' option in %q, please specify:\n"+
|
2019-09-07 13:06:27 -07:00
|
|
|
"\toption go_package = %q;\n"+
|
|
|
|
"A future release of protoc-gen-go will reject this.\n"+
|
2020-02-24 11:21:30 -08:00
|
|
|
"See "+goPackageDocURL+" for more information.\n"+
|
2019-09-07 13:06:27 -07:00
|
|
|
"\n", d.GetName(), string(impPath)+";"+string(pkg))
|
|
|
|
}
|
|
|
|
return pkg, impPath
|
|
|
|
}
|
|
|
|
func goPackageOptionRaw(opt string) (rawPkg string, impPath GoImportPath) {
|
2018-09-06 10:23:53 -07:00
|
|
|
// A semicolon-delimited suffix delimits the import path and package name.
|
|
|
|
if i := strings.Index(opt, ";"); i >= 0 {
|
2019-09-07 13:06:27 -07:00
|
|
|
return opt[i+1:], GoImportPath(opt[:i])
|
2018-09-06 10:23:53 -07:00
|
|
|
}
|
|
|
|
// The presence of a slash implies there's an import path.
|
|
|
|
if i := strings.LastIndex(opt, "/"); i >= 0 {
|
2019-09-07 13:06:27 -07:00
|
|
|
return opt[i+1:], GoImportPath(opt)
|
2018-09-06 10:23:53 -07:00
|
|
|
}
|
2019-09-07 13:06:27 -07:00
|
|
|
return opt, ""
|
2018-09-06 10:23:53 -07:00
|
|
|
}
|
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
// An Enum describes an enum.
|
|
|
|
type Enum struct {
|
|
|
|
Desc protoreflect.EnumDescriptor
|
|
|
|
|
|
|
|
GoIdent GoIdent // name of the generated Go type
|
|
|
|
|
|
|
|
Values []*EnumValue // enum value declarations
|
|
|
|
|
|
|
|
Location Location // location of this enum
|
|
|
|
Comments CommentSet // comments associated with this enum
|
|
|
|
}
|
|
|
|
|
|
|
|
func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
|
|
|
|
var loc Location
|
|
|
|
if parent != nil {
|
|
|
|
loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index()))
|
|
|
|
} else {
|
|
|
|
loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index()))
|
|
|
|
}
|
|
|
|
enum := &Enum{
|
|
|
|
Desc: desc,
|
|
|
|
GoIdent: newGoIdent(f, desc),
|
|
|
|
Location: loc,
|
|
|
|
Comments: f.comments[newPathKey(loc.Path)],
|
|
|
|
}
|
|
|
|
gen.enumsByName[desc.FullName()] = enum
|
|
|
|
for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
|
|
|
|
enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
|
|
|
|
}
|
|
|
|
return enum
|
|
|
|
}
|
|
|
|
|
|
|
|
// An EnumValue describes an enum value.
|
|
|
|
type EnumValue struct {
|
|
|
|
Desc protoreflect.EnumValueDescriptor
|
|
|
|
|
|
|
|
GoIdent GoIdent // name of the generated Go declaration
|
|
|
|
|
2019-08-20 22:26:16 -07:00
|
|
|
Parent *Enum // enum in which this value is declared
|
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
Location Location // location of this enum value
|
|
|
|
Comments CommentSet // comments associated with this enum value
|
|
|
|
}
|
|
|
|
|
|
|
|
func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
|
|
|
|
// A top-level enum value's name is: EnumName_ValueName
|
|
|
|
// An enum value contained in a message is: MessageName_ValueName
|
|
|
|
//
|
2019-08-21 00:55:36 -07:00
|
|
|
// For historical reasons, enum value names are not camel-cased.
|
2019-08-20 20:10:23 -07:00
|
|
|
parentIdent := enum.GoIdent
|
|
|
|
if message != nil {
|
|
|
|
parentIdent = message.GoIdent
|
|
|
|
}
|
|
|
|
name := parentIdent.GoName + "_" + string(desc.Name())
|
|
|
|
loc := enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index()))
|
|
|
|
return &EnumValue{
|
|
|
|
Desc: desc,
|
|
|
|
GoIdent: f.GoImportPath.Ident(name),
|
2019-08-20 22:26:16 -07:00
|
|
|
Parent: enum,
|
2019-08-20 20:10:23 -07:00
|
|
|
Location: loc,
|
|
|
|
Comments: f.comments[newPathKey(loc.Path)],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-22 13:46:02 -07:00
|
|
|
// A Message describes a message.
|
|
|
|
type Message struct {
|
2018-08-23 14:39:30 -07:00
|
|
|
Desc protoreflect.MessageDescriptor
|
2018-08-22 13:46:02 -07:00
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
GoIdent GoIdent // name of the generated Go type
|
|
|
|
|
|
|
|
Fields []*Field // message field declarations
|
|
|
|
Oneofs []*Oneof // message oneof declarations
|
|
|
|
|
2018-09-14 15:41:11 -07:00
|
|
|
Enums []*Enum // nested enum declarations
|
2019-08-20 20:10:23 -07:00
|
|
|
Messages []*Message // nested message declarations
|
2018-09-14 15:41:11 -07:00
|
|
|
Extensions []*Extension // nested extension declarations
|
2019-08-20 20:10:23 -07:00
|
|
|
|
|
|
|
Location Location // location of this message
|
|
|
|
Comments CommentSet // comments associated with this message
|
2018-08-22 13:46:02 -07:00
|
|
|
}
|
|
|
|
|
2018-09-13 13:12:36 -07:00
|
|
|
func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
|
2018-10-04 12:42:37 -07:00
|
|
|
var loc Location
|
2018-09-06 14:51:28 -07:00
|
|
|
if parent != nil {
|
2019-03-20 16:51:09 -07:00
|
|
|
loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index()))
|
2018-09-06 14:51:28 -07:00
|
|
|
} else {
|
2019-03-20 16:51:09 -07:00
|
|
|
loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index()))
|
2018-09-06 14:51:28 -07:00
|
|
|
}
|
2018-09-07 12:45:37 -07:00
|
|
|
message := &Message{
|
2018-10-04 12:42:37 -07:00
|
|
|
Desc: desc,
|
|
|
|
GoIdent: newGoIdent(f, desc),
|
|
|
|
Location: loc,
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Comments: f.comments[newPathKey(loc.Path)],
|
2018-08-22 13:46:02 -07:00
|
|
|
}
|
2018-09-10 12:26:21 -07:00
|
|
|
gen.messagesByName[desc.FullName()] = message
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
|
|
|
|
message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
|
2018-09-07 12:45:37 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
|
|
|
|
message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
|
2018-09-07 12:45:37 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
|
|
|
|
message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
|
2018-09-13 13:12:36 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
|
|
|
|
message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
|
2018-09-10 12:26:21 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
|
|
|
|
message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Resolve local references between fields and oneofs.
|
|
|
|
for _, field := range message.Fields {
|
|
|
|
if od := field.Desc.ContainingOneof(); od != nil {
|
|
|
|
oneof := message.Oneofs[od.Index()]
|
|
|
|
field.Oneof = oneof
|
|
|
|
oneof.Fields = append(oneof.Fields, field)
|
|
|
|
}
|
2018-09-14 15:41:11 -07:00
|
|
|
}
|
2018-09-10 12:26:21 -07:00
|
|
|
|
|
|
|
// Field name conflict resolution.
|
|
|
|
//
|
|
|
|
// We assume well-known method names that may be attached to a generated
|
|
|
|
// message type, as well as a 'Get*' method for each field. For each
|
|
|
|
// field in turn, we add _s to its name until there are no conflicts.
|
|
|
|
//
|
|
|
|
// Any change to the following set of method names is a potential
|
|
|
|
// incompatible API change because it may change generated field names.
|
|
|
|
//
|
|
|
|
// TODO: If we ever support a 'go_name' option to set the Go name of a
|
|
|
|
// field, we should consider dropping this entirely. The conflict
|
|
|
|
// resolution algorithm is subtle and surprising (changing the order
|
|
|
|
// in which fields appear in the .proto source file can change the
|
|
|
|
// names of fields in generated code), and does not adapt well to
|
|
|
|
// adding new per-field methods such as setters.
|
|
|
|
usedNames := map[string]bool{
|
|
|
|
"Reset": true,
|
|
|
|
"String": true,
|
|
|
|
"ProtoMessage": true,
|
|
|
|
"Marshal": true,
|
|
|
|
"Unmarshal": true,
|
|
|
|
"ExtensionRangeArray": true,
|
|
|
|
"ExtensionMap": true,
|
|
|
|
"Descriptor": true,
|
|
|
|
}
|
2019-01-08 10:59:34 -08:00
|
|
|
makeNameUnique := func(name string, hasGetter bool) string {
|
|
|
|
for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
|
2018-09-10 12:26:21 -07:00
|
|
|
name += "_"
|
|
|
|
}
|
|
|
|
usedNames[name] = true
|
2019-01-08 10:59:34 -08:00
|
|
|
usedNames["Get"+name] = hasGetter
|
2018-09-10 12:26:21 -07:00
|
|
|
return name
|
|
|
|
}
|
|
|
|
for _, field := range message.Fields {
|
2019-01-08 10:59:34 -08:00
|
|
|
field.GoName = makeNameUnique(field.GoName, true)
|
2019-08-21 00:55:36 -07:00
|
|
|
field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName
|
|
|
|
if field.Oneof != nil && field.Oneof.Fields[0] == field {
|
|
|
|
// Make the name for a oneof unique as well. For historical reasons,
|
|
|
|
// this assumes that a getter method is not generated for oneofs.
|
|
|
|
// This is incorrect, but fixing it breaks existing code.
|
|
|
|
field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
|
|
|
|
field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Oneof field name conflict resolution.
|
|
|
|
//
|
|
|
|
// This conflict resolution is incomplete as it does not consider collisions
|
|
|
|
// with other oneof field types, but fixing it breaks existing code.
|
|
|
|
for _, field := range message.Fields {
|
2019-04-15 23:39:09 -07:00
|
|
|
if field.Oneof != nil {
|
2019-08-21 00:55:36 -07:00
|
|
|
Loop:
|
|
|
|
for {
|
|
|
|
for _, nestedMessage := range message.Messages {
|
|
|
|
if nestedMessage.GoIdent == field.GoIdent {
|
|
|
|
field.GoIdent.GoName += "_"
|
|
|
|
continue Loop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, nestedEnum := range message.Enums {
|
|
|
|
if nestedEnum.GoIdent == field.GoIdent {
|
|
|
|
field.GoIdent.GoName += "_"
|
|
|
|
continue Loop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
break Loop
|
2018-09-13 13:12:36 -07:00
|
|
|
}
|
|
|
|
}
|
2018-09-10 12:26:21 -07:00
|
|
|
}
|
|
|
|
|
2018-09-13 13:12:36 -07:00
|
|
|
return message
|
2018-09-10 12:26:21 -07:00
|
|
|
}
|
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
func (message *Message) resolveDependencies(gen *Plugin) error {
|
|
|
|
for _, field := range message.Fields {
|
|
|
|
if err := field.resolveDependencies(gen); err != nil {
|
2018-09-13 15:07:10 -07:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for _, message := range message.Messages {
|
|
|
|
if err := message.resolveDependencies(gen); err != nil {
|
2018-09-13 15:07:10 -07:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2018-09-14 15:41:11 -07:00
|
|
|
for _, extension := range message.Extensions {
|
2019-08-20 20:10:23 -07:00
|
|
|
if err := extension.resolveDependencies(gen); err != nil {
|
2018-09-14 15:41:11 -07:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2018-09-13 15:07:10 -07:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-09-10 12:26:21 -07:00
|
|
|
// A Field describes a message field.
|
|
|
|
type Field struct {
|
|
|
|
Desc protoreflect.FieldDescriptor
|
|
|
|
|
2018-09-13 13:12:36 -07:00
|
|
|
// GoName is the base name of this field's Go field and methods.
|
2018-09-10 12:26:21 -07:00
|
|
|
// For code generated by protoc-gen-go, this means a field named
|
2018-09-13 13:12:36 -07:00
|
|
|
// '{{GoName}}' and a getter method named 'Get{{GoName}}'.
|
2019-08-21 00:55:36 -07:00
|
|
|
GoName string // e.g., "FieldName"
|
|
|
|
|
|
|
|
// GoIdent is the base name of a top-level declaration for this field.
|
|
|
|
// For code generated by protoc-gen-go, this means a wrapper type named
|
|
|
|
// '{{GoIdent}}' for members fields of a oneof, and a variable named
|
|
|
|
// 'E_{{GoIdent}}' for extension fields.
|
|
|
|
GoIdent GoIdent // e.g., "MessageName_FieldName"
|
2018-09-13 13:12:36 -07:00
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
Parent *Message // message in which this field is declared; nil if top-level extension
|
|
|
|
Oneof *Oneof // containing oneof; nil if not part of a oneof
|
|
|
|
Extendee *Message // extended message for extension fields; nil otherwise
|
|
|
|
|
|
|
|
Enum *Enum // type for enum fields; nil otherwise
|
|
|
|
Message *Message // type for message or group fields; nil otherwise
|
|
|
|
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Location Location // location of this field
|
|
|
|
Comments CommentSet // comments associated with this field
|
2018-09-10 12:26:21 -07:00
|
|
|
}
|
|
|
|
|
2018-09-13 13:12:36 -07:00
|
|
|
func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
|
2018-10-04 12:42:37 -07:00
|
|
|
var loc Location
|
2018-09-14 15:41:11 -07:00
|
|
|
switch {
|
2019-05-13 14:32:56 -07:00
|
|
|
case desc.IsExtension() && message == nil:
|
2019-03-20 16:51:09 -07:00
|
|
|
loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index()))
|
2019-05-13 14:32:56 -07:00
|
|
|
case desc.IsExtension() && message != nil:
|
2019-03-20 16:51:09 -07:00
|
|
|
loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index()))
|
2018-09-14 15:41:11 -07:00
|
|
|
default:
|
2019-03-20 16:51:09 -07:00
|
|
|
loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index()))
|
2018-09-14 15:41:11 -07:00
|
|
|
}
|
2019-08-23 12:18:57 -07:00
|
|
|
camelCased := strs.GoCamelCase(string(desc.Name()))
|
2019-08-21 00:55:36 -07:00
|
|
|
var parentPrefix string
|
|
|
|
if message != nil {
|
|
|
|
parentPrefix = message.GoIdent.GoName + "_"
|
|
|
|
}
|
2018-09-10 12:26:21 -07:00
|
|
|
field := &Field{
|
2019-08-21 00:55:36 -07:00
|
|
|
Desc: desc,
|
|
|
|
GoName: camelCased,
|
|
|
|
GoIdent: GoIdent{
|
|
|
|
GoImportPath: f.GoImportPath,
|
|
|
|
GoName: parentPrefix + camelCased,
|
|
|
|
},
|
2019-04-15 23:39:09 -07:00
|
|
|
Parent: message,
|
|
|
|
Location: loc,
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Comments: f.comments[newPathKey(loc.Path)],
|
2018-09-13 13:12:36 -07:00
|
|
|
}
|
|
|
|
return field
|
2018-09-13 15:07:10 -07:00
|
|
|
}
|
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
func (field *Field) resolveDependencies(gen *Plugin) error {
|
2018-09-13 15:07:10 -07:00
|
|
|
desc := field.Desc
|
2018-09-10 12:26:21 -07:00
|
|
|
switch desc.Kind() {
|
|
|
|
case protoreflect.EnumKind:
|
2019-08-20 20:10:23 -07:00
|
|
|
name := field.Desc.Enum().FullName()
|
|
|
|
enum, ok := gen.enumsByName[name]
|
2018-09-10 12:26:21 -07:00
|
|
|
if !ok {
|
2019-08-20 20:10:23 -07:00
|
|
|
return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
|
2018-09-10 12:26:21 -07:00
|
|
|
}
|
2019-04-15 23:39:09 -07:00
|
|
|
field.Enum = enum
|
2019-08-20 20:10:23 -07:00
|
|
|
case protoreflect.MessageKind, protoreflect.GroupKind:
|
|
|
|
name := desc.Message().FullName()
|
|
|
|
message, ok := gen.messagesByName[name]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
|
|
|
|
}
|
|
|
|
field.Message = message
|
2018-09-10 12:26:21 -07:00
|
|
|
}
|
2019-05-13 14:32:56 -07:00
|
|
|
if desc.IsExtension() {
|
2019-08-20 20:10:23 -07:00
|
|
|
name := desc.ContainingMessage().FullName()
|
|
|
|
message, ok := gen.messagesByName[name]
|
2018-09-14 15:41:11 -07:00
|
|
|
if !ok {
|
2019-08-20 20:10:23 -07:00
|
|
|
return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
|
2018-09-14 15:41:11 -07:00
|
|
|
}
|
2019-04-15 23:39:09 -07:00
|
|
|
field.Extendee = message
|
2018-09-14 15:41:11 -07:00
|
|
|
}
|
2018-09-13 15:07:10 -07:00
|
|
|
return nil
|
2018-09-07 12:45:37 -07:00
|
|
|
}
|
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
// A Oneof describes a message oneof.
|
2018-09-13 13:12:36 -07:00
|
|
|
type Oneof struct {
|
|
|
|
Desc protoreflect.OneofDescriptor
|
|
|
|
|
2019-08-21 00:55:36 -07:00
|
|
|
// GoName is the base name of this oneof's Go field and methods.
|
|
|
|
// For code generated by protoc-gen-go, this means a field named
|
|
|
|
// '{{GoName}}' and a getter method named 'Get{{GoName}}'.
|
|
|
|
GoName string // e.g., "OneofName"
|
|
|
|
|
|
|
|
// GoIdent is the base name of a top-level declaration for this oneof.
|
|
|
|
GoIdent GoIdent // e.g., "MessageName_OneofName"
|
2019-08-20 20:10:23 -07:00
|
|
|
|
|
|
|
Parent *Message // message in which this oneof is declared
|
|
|
|
|
2019-04-15 23:39:09 -07:00
|
|
|
Fields []*Field // fields that are part of this oneof
|
|
|
|
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Location Location // location of this oneof
|
|
|
|
Comments CommentSet // comments associated with this oneof
|
2018-09-13 13:12:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
loc := message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index()))
|
2019-08-23 12:18:57 -07:00
|
|
|
camelCased := strs.GoCamelCase(string(desc.Name()))
|
2019-08-21 00:55:36 -07:00
|
|
|
parentPrefix := message.GoIdent.GoName + "_"
|
2018-09-13 13:12:36 -07:00
|
|
|
return &Oneof{
|
2019-08-21 00:55:36 -07:00
|
|
|
Desc: desc,
|
|
|
|
Parent: message,
|
|
|
|
GoName: camelCased,
|
|
|
|
GoIdent: GoIdent{
|
|
|
|
GoImportPath: f.GoImportPath,
|
|
|
|
GoName: parentPrefix + camelCased,
|
|
|
|
},
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Location: loc,
|
|
|
|
Comments: f.comments[newPathKey(loc.Path)],
|
2018-09-13 13:12:36 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
// Extension is an alias of Field for documentation.
|
|
|
|
type Extension = Field
|
2018-08-15 11:24:18 -07:00
|
|
|
|
2018-09-21 15:03:34 -07:00
|
|
|
// A Service describes a service.
|
|
|
|
type Service struct {
|
|
|
|
Desc protoreflect.ServiceDescriptor
|
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
GoName string
|
|
|
|
|
|
|
|
Methods []*Method // service method declarations
|
2019-04-15 23:39:09 -07:00
|
|
|
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Location Location // location of this service
|
|
|
|
Comments CommentSet // comments associated with this service
|
2018-09-21 15:03:34 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
loc := f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index()))
|
2018-09-21 15:03:34 -07:00
|
|
|
service := &Service{
|
2018-10-04 12:42:37 -07:00
|
|
|
Desc: desc,
|
2019-08-23 12:18:57 -07:00
|
|
|
GoName: strs.GoCamelCase(string(desc.Name())),
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Location: loc,
|
|
|
|
Comments: f.comments[newPathKey(loc.Path)],
|
2018-09-21 15:03:34 -07:00
|
|
|
}
|
2019-08-20 20:10:23 -07:00
|
|
|
for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
|
|
|
|
service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
|
2018-09-21 15:03:34 -07:00
|
|
|
}
|
|
|
|
return service
|
|
|
|
}
|
|
|
|
|
|
|
|
// A Method describes a method in a service.
|
|
|
|
type Method struct {
|
|
|
|
Desc protoreflect.MethodDescriptor
|
|
|
|
|
2019-04-15 23:39:09 -07:00
|
|
|
GoName string
|
2019-08-20 20:10:23 -07:00
|
|
|
|
|
|
|
Parent *Service // service in which this method is declared
|
|
|
|
|
2019-04-15 23:39:09 -07:00
|
|
|
Input *Message
|
|
|
|
Output *Message
|
|
|
|
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Location Location // location of this method
|
|
|
|
Comments CommentSet // comments associated with this method
|
2018-09-21 15:03:34 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
loc := service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index()))
|
2018-09-21 15:03:34 -07:00
|
|
|
method := &Method{
|
2019-04-15 23:39:09 -07:00
|
|
|
Desc: desc,
|
2019-08-23 12:18:57 -07:00
|
|
|
GoName: strs.GoCamelCase(string(desc.Name())),
|
2019-04-15 23:39:09 -07:00
|
|
|
Parent: service,
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
Location: loc,
|
|
|
|
Comments: f.comments[newPathKey(loc.Path)],
|
2018-09-21 15:03:34 -07:00
|
|
|
}
|
|
|
|
return method
|
|
|
|
}
|
|
|
|
|
2019-08-20 20:10:23 -07:00
|
|
|
func (method *Method) resolveDependencies(gen *Plugin) error {
|
2018-09-21 15:03:34 -07:00
|
|
|
desc := method.Desc
|
|
|
|
|
2019-04-15 23:39:09 -07:00
|
|
|
inName := desc.Input().FullName()
|
2018-09-21 15:03:34 -07:00
|
|
|
in, ok := gen.messagesByName[inName]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
|
|
|
|
}
|
2019-04-15 23:39:09 -07:00
|
|
|
method.Input = in
|
2018-09-21 15:03:34 -07:00
|
|
|
|
2019-04-15 23:39:09 -07:00
|
|
|
outName := desc.Output().FullName()
|
2018-09-21 15:03:34 -07:00
|
|
|
out, ok := gen.messagesByName[outName]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
|
|
|
|
}
|
2019-04-15 23:39:09 -07:00
|
|
|
method.Output = out
|
2018-09-21 15:03:34 -07:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-12-21 15:54:06 -08:00
|
|
|
// A GeneratedFile is a generated file.
|
|
|
|
type GeneratedFile struct {
|
|
|
|
gen *Plugin
|
|
|
|
skip bool
|
|
|
|
filename string
|
|
|
|
goImportPath GoImportPath
|
|
|
|
buf bytes.Buffer
|
|
|
|
packageNames map[GoImportPath]GoPackageName
|
|
|
|
usedPackageNames map[GoPackageName]bool
|
|
|
|
manualImports map[GoImportPath]bool
|
|
|
|
annotations map[string][]Location
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewGeneratedFile creates a new generated file with the given filename
|
|
|
|
// and import path.
|
|
|
|
func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
|
|
|
|
g := &GeneratedFile{
|
|
|
|
gen: gen,
|
|
|
|
filename: filename,
|
|
|
|
goImportPath: goImportPath,
|
|
|
|
packageNames: make(map[GoImportPath]GoPackageName),
|
|
|
|
usedPackageNames: make(map[GoPackageName]bool),
|
|
|
|
manualImports: make(map[GoImportPath]bool),
|
|
|
|
annotations: make(map[string][]Location),
|
|
|
|
}
|
2019-01-14 11:48:43 -08:00
|
|
|
|
|
|
|
// All predeclared identifiers in Go are already used.
|
|
|
|
for _, s := range types.Universe.Names() {
|
|
|
|
g.usedPackageNames[GoPackageName(s)] = true
|
|
|
|
}
|
|
|
|
|
2018-12-21 15:54:06 -08:00
|
|
|
gen.genFiles = append(gen.genFiles, g)
|
|
|
|
return g
|
|
|
|
}
|
|
|
|
|
2018-08-15 11:24:18 -07:00
|
|
|
// P prints a line to the generated output. It converts each parameter to a
|
|
|
|
// string following the same rules as fmt.Print. It never inserts spaces
|
|
|
|
// between parameters.
|
|
|
|
func (g *GeneratedFile) P(v ...interface{}) {
|
|
|
|
for _, x := range v {
|
2018-08-23 14:39:30 -07:00
|
|
|
switch x := x.(type) {
|
|
|
|
case GoIdent:
|
2018-09-07 12:45:37 -07:00
|
|
|
fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
|
2018-08-23 14:39:30 -07:00
|
|
|
default:
|
|
|
|
fmt.Fprint(&g.buf, x)
|
|
|
|
}
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
|
|
|
fmt.Fprintln(&g.buf)
|
|
|
|
}
|
|
|
|
|
2018-09-07 12:45:37 -07:00
|
|
|
// QualifiedGoIdent returns the string to use for a Go identifier.
|
|
|
|
//
|
|
|
|
// If the identifier is from a different Go package than the generated file,
|
|
|
|
// the returned name will be qualified (package.name) and an import statement
|
|
|
|
// for the identifier's package will be included in the file.
|
|
|
|
func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
|
|
|
|
if ident.GoImportPath == g.goImportPath {
|
|
|
|
return ident.GoName
|
|
|
|
}
|
|
|
|
if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
|
|
|
|
return string(packageName) + "." + ident.GoName
|
|
|
|
}
|
|
|
|
packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
|
2019-01-14 11:48:43 -08:00
|
|
|
for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
|
2018-09-07 12:45:37 -07:00
|
|
|
packageName = orig + GoPackageName(strconv.Itoa(i))
|
|
|
|
}
|
|
|
|
g.packageNames[ident.GoImportPath] = packageName
|
|
|
|
g.usedPackageNames[packageName] = true
|
|
|
|
return string(packageName) + "." + ident.GoName
|
|
|
|
}
|
|
|
|
|
2018-09-19 12:51:36 -07:00
|
|
|
// Import ensures a package is imported by the generated file.
|
|
|
|
//
|
|
|
|
// Packages referenced by QualifiedGoIdent are automatically imported.
|
|
|
|
// Explicitly importing a package with Import is generally only necessary
|
|
|
|
// when the import will be blank (import _ "package").
|
|
|
|
func (g *GeneratedFile) Import(importPath GoImportPath) {
|
|
|
|
g.manualImports[importPath] = true
|
|
|
|
}
|
|
|
|
|
2018-08-15 11:24:18 -07:00
|
|
|
// Write implements io.Writer.
|
|
|
|
func (g *GeneratedFile) Write(p []byte) (n int, err error) {
|
|
|
|
return g.buf.Write(p)
|
|
|
|
}
|
|
|
|
|
2018-12-21 15:54:06 -08:00
|
|
|
// Skip removes the generated file from the plugin output.
|
|
|
|
func (g *GeneratedFile) Skip() {
|
|
|
|
g.skip = true
|
|
|
|
}
|
|
|
|
|
2020-05-06 06:04:40 +02:00
|
|
|
// Unskip reverts a previous call to Skip, re-including the generated file in
|
|
|
|
// the plugin output.
|
|
|
|
func (g *GeneratedFile) Unskip() {
|
|
|
|
g.skip = false
|
|
|
|
}
|
|
|
|
|
2018-10-04 12:42:37 -07:00
|
|
|
// Annotate associates a symbol in a generated Go file with a location in a
|
|
|
|
// source .proto file.
|
|
|
|
//
|
|
|
|
// The symbol may refer to a type, constant, variable, function, method, or
|
|
|
|
// struct field. The "T.sel" syntax is used to identify the method or field
|
|
|
|
// 'sel' on type 'T'.
|
|
|
|
func (g *GeneratedFile) Annotate(symbol string, loc Location) {
|
|
|
|
g.annotations[symbol] = append(g.annotations[symbol], loc)
|
|
|
|
}
|
|
|
|
|
2018-12-21 15:54:06 -08:00
|
|
|
// Content returns the contents of the generated file.
|
|
|
|
func (g *GeneratedFile) Content() ([]byte, error) {
|
2018-08-23 14:39:30 -07:00
|
|
|
if !strings.HasSuffix(g.filename, ".go") {
|
2018-08-22 13:46:02 -07:00
|
|
|
return g.buf.Bytes(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reformat generated code.
|
|
|
|
original := g.buf.Bytes()
|
|
|
|
fset := token.NewFileSet()
|
2018-09-13 13:12:36 -07:00
|
|
|
file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
|
2018-08-22 13:46:02 -07:00
|
|
|
if err != nil {
|
|
|
|
// Print out the bad code with line numbers.
|
|
|
|
// This should never happen in practice, but it can while changing generated code
|
|
|
|
// so consider this a debugging aid.
|
|
|
|
var src bytes.Buffer
|
|
|
|
s := bufio.NewScanner(bytes.NewReader(original))
|
|
|
|
for line := 1; s.Scan(); line++ {
|
|
|
|
fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
|
|
|
|
}
|
2018-08-23 14:39:30 -07:00
|
|
|
return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
|
|
|
|
}
|
|
|
|
|
2019-03-10 16:40:48 -07:00
|
|
|
// Collect a sorted list of all imports.
|
|
|
|
var importPaths [][2]string
|
2018-09-27 15:51:05 -07:00
|
|
|
rewriteImport := func(importPath string) string {
|
|
|
|
if f := g.gen.opts.ImportRewriteFunc; f != nil {
|
|
|
|
return string(f(GoImportPath(importPath)))
|
|
|
|
}
|
|
|
|
return importPath
|
|
|
|
}
|
2019-03-10 16:40:48 -07:00
|
|
|
for importPath := range g.packageNames {
|
|
|
|
pkgName := string(g.packageNames[GoImportPath(importPath)])
|
|
|
|
pkgPath := rewriteImport(string(importPath))
|
|
|
|
importPaths = append(importPaths, [2]string{pkgName, pkgPath})
|
2018-08-22 13:46:02 -07:00
|
|
|
}
|
2018-09-19 12:51:36 -07:00
|
|
|
for importPath := range g.manualImports {
|
2019-03-10 16:40:48 -07:00
|
|
|
if _, ok := g.packageNames[importPath]; !ok {
|
|
|
|
pkgPath := rewriteImport(string(importPath))
|
|
|
|
importPaths = append(importPaths, [2]string{"_", pkgPath})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
sort.Slice(importPaths, func(i, j int) bool {
|
|
|
|
return importPaths[i][1] < importPaths[j][1]
|
|
|
|
})
|
|
|
|
|
|
|
|
// Modify the AST to include a new import block.
|
|
|
|
if len(importPaths) > 0 {
|
|
|
|
// Insert block after package statement or
|
|
|
|
// possible comment attached to the end of the package statement.
|
|
|
|
pos := file.Package
|
|
|
|
tokFile := fset.File(file.Package)
|
|
|
|
pkgLine := tokFile.Line(file.Package)
|
|
|
|
for _, c := range file.Comments {
|
|
|
|
if tokFile.Line(c.Pos()) > pkgLine {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
pos = c.End()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Construct the import block.
|
|
|
|
impDecl := &ast.GenDecl{
|
|
|
|
Tok: token.IMPORT,
|
|
|
|
TokPos: pos,
|
|
|
|
Lparen: pos,
|
|
|
|
Rparen: pos,
|
|
|
|
}
|
|
|
|
for _, importPath := range importPaths {
|
|
|
|
impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
|
|
|
|
Name: &ast.Ident{
|
|
|
|
Name: importPath[0],
|
|
|
|
NamePos: pos,
|
|
|
|
},
|
|
|
|
Path: &ast.BasicLit{
|
|
|
|
Kind: token.STRING,
|
|
|
|
Value: strconv.Quote(importPath[1]),
|
|
|
|
ValuePos: pos,
|
|
|
|
},
|
|
|
|
EndPos: pos,
|
|
|
|
})
|
2018-09-19 12:51:36 -07:00
|
|
|
}
|
2019-03-10 16:40:48 -07:00
|
|
|
file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
|
2018-09-19 12:51:36 -07:00
|
|
|
}
|
2018-08-23 14:39:30 -07:00
|
|
|
|
2018-08-22 13:46:02 -07:00
|
|
|
var out bytes.Buffer
|
2018-09-13 13:12:36 -07:00
|
|
|
if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
|
2018-08-23 14:39:30 -07:00
|
|
|
return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
|
2018-08-22 13:46:02 -07:00
|
|
|
}
|
|
|
|
return out.Bytes(), nil
|
2018-10-04 12:42:37 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// metaFile returns the contents of the file's metadata file, which is a
|
|
|
|
// text formatted string of the google.protobuf.GeneratedCodeInfo.
|
|
|
|
func (g *GeneratedFile) metaFile(content []byte) (string, error) {
|
|
|
|
fset := token.NewFileSet()
|
|
|
|
astFile, err := parser.ParseFile(fset, "", content, 0)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2018-11-26 18:55:29 -08:00
|
|
|
info := &descriptorpb.GeneratedCodeInfo{}
|
2018-10-04 12:42:37 -07:00
|
|
|
|
|
|
|
seenAnnotations := make(map[string]bool)
|
|
|
|
annotate := func(s string, ident *ast.Ident) {
|
|
|
|
seenAnnotations[s] = true
|
|
|
|
for _, loc := range g.annotations[s] {
|
2018-11-26 18:55:29 -08:00
|
|
|
info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
|
2019-07-10 16:17:16 -07:00
|
|
|
SourceFile: proto.String(loc.SourceFile),
|
2018-10-04 12:42:37 -07:00
|
|
|
Path: loc.Path,
|
2019-07-10 16:17:16 -07:00
|
|
|
Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
|
|
|
|
End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
|
2018-10-04 12:42:37 -07:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, decl := range astFile.Decls {
|
|
|
|
switch decl := decl.(type) {
|
|
|
|
case *ast.GenDecl:
|
|
|
|
for _, spec := range decl.Specs {
|
|
|
|
switch spec := spec.(type) {
|
|
|
|
case *ast.TypeSpec:
|
|
|
|
annotate(spec.Name.Name, spec.Name)
|
2018-12-12 08:54:57 -08:00
|
|
|
switch st := spec.Type.(type) {
|
|
|
|
case *ast.StructType:
|
2018-10-04 12:42:37 -07:00
|
|
|
for _, field := range st.Fields.List {
|
|
|
|
for _, name := range field.Names {
|
|
|
|
annotate(spec.Name.Name+"."+name.Name, name)
|
|
|
|
}
|
|
|
|
}
|
2018-12-12 08:54:57 -08:00
|
|
|
case *ast.InterfaceType:
|
|
|
|
for _, field := range st.Methods.List {
|
|
|
|
for _, name := range field.Names {
|
|
|
|
annotate(spec.Name.Name+"."+name.Name, name)
|
|
|
|
}
|
|
|
|
}
|
2018-10-04 12:42:37 -07:00
|
|
|
}
|
|
|
|
case *ast.ValueSpec:
|
|
|
|
for _, name := range spec.Names {
|
|
|
|
annotate(name.Name, name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case *ast.FuncDecl:
|
|
|
|
if decl.Recv == nil {
|
|
|
|
annotate(decl.Name.Name, decl.Name)
|
|
|
|
} else {
|
|
|
|
recv := decl.Recv.List[0].Type
|
|
|
|
if s, ok := recv.(*ast.StarExpr); ok {
|
|
|
|
recv = s.X
|
|
|
|
}
|
|
|
|
if id, ok := recv.(*ast.Ident); ok {
|
|
|
|
annotate(id.Name+"."+decl.Name.Name, decl.Name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for a := range g.annotations {
|
|
|
|
if !seenAnnotations[a] {
|
|
|
|
return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
|
|
|
|
}
|
|
|
|
}
|
2018-08-22 13:46:02 -07:00
|
|
|
|
2019-05-14 12:44:37 -07:00
|
|
|
b, err := prototext.Marshal(info)
|
2019-03-18 14:54:34 -07:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return string(b), nil
|
2018-08-15 11:24:18 -07:00
|
|
|
}
|
2018-09-06 10:23:53 -07:00
|
|
|
|
2019-08-23 12:18:57 -07:00
|
|
|
// A GoIdent is a Go identifier, consisting of a name and import path.
|
|
|
|
// The name is a single identifier and may not be a dot-qualified selector.
|
|
|
|
type GoIdent struct {
|
|
|
|
GoName string
|
|
|
|
GoImportPath GoImportPath
|
|
|
|
}
|
|
|
|
|
|
|
|
func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
|
|
|
|
|
|
|
|
// newGoIdent returns the Go identifier for a descriptor.
|
|
|
|
func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
|
|
|
|
name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
|
|
|
|
return GoIdent{
|
|
|
|
GoName: strs.GoCamelCase(name),
|
|
|
|
GoImportPath: f.GoImportPath,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// A GoImportPath is the import path of a Go package.
|
|
|
|
// For example: "google.golang.org/protobuf/compiler/protogen"
|
|
|
|
type GoImportPath string
|
|
|
|
|
|
|
|
func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
|
|
|
|
|
|
|
|
// Ident returns a GoIdent with s as the GoName and p as the GoImportPath.
|
|
|
|
func (p GoImportPath) Ident(s string) GoIdent {
|
|
|
|
return GoIdent{GoName: s, GoImportPath: p}
|
|
|
|
}
|
|
|
|
|
|
|
|
// A GoPackageName is the name of a Go package. e.g., "protobuf".
|
|
|
|
type GoPackageName string
|
|
|
|
|
|
|
|
// cleanPackageName converts a string to a valid Go package name.
|
|
|
|
func cleanPackageName(name string) GoPackageName {
|
|
|
|
return GoPackageName(strs.GoSanitized(name))
|
|
|
|
}
|
|
|
|
|
|
|
|
// baseName returns the last path element of the name, with the last dotted suffix removed.
|
|
|
|
func baseName(name string) string {
|
|
|
|
// First, find the last element
|
|
|
|
if i := strings.LastIndex(name, "/"); i >= 0 {
|
|
|
|
name = name[i+1:]
|
|
|
|
}
|
|
|
|
// Now drop the suffix
|
|
|
|
if i := strings.LastIndex(name, "."); i >= 0 {
|
|
|
|
name = name[:i]
|
|
|
|
}
|
|
|
|
return name
|
|
|
|
}
|
|
|
|
|
2018-09-06 10:23:53 -07:00
|
|
|
type pathType int
|
|
|
|
|
|
|
|
const (
|
2020-02-15 14:28:51 -08:00
|
|
|
pathTypeLegacy pathType = iota
|
|
|
|
pathTypeImport
|
2018-09-06 10:23:53 -07:00
|
|
|
pathTypeSourceRelative
|
|
|
|
)
|
2018-09-06 14:51:28 -07:00
|
|
|
|
2018-10-04 12:42:37 -07:00
|
|
|
// A Location is a location in a .proto source file.
|
|
|
|
//
|
|
|
|
// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
|
|
|
|
// for details.
|
|
|
|
type Location struct {
|
|
|
|
SourceFile string
|
2019-07-12 17:16:36 -07:00
|
|
|
Path protoreflect.SourcePath
|
2018-10-04 12:42:37 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// appendPath add elements to a Location's path, returning a new Location.
|
|
|
|
func (loc Location) appendPath(a ...int32) Location {
|
2019-07-12 17:16:36 -07:00
|
|
|
var n protoreflect.SourcePath
|
2018-10-04 12:42:37 -07:00
|
|
|
n = append(n, loc.Path...)
|
2018-09-06 14:51:28 -07:00
|
|
|
n = append(n, a...)
|
2018-10-04 12:42:37 -07:00
|
|
|
return Location{
|
|
|
|
SourceFile: loc.SourceFile,
|
|
|
|
Path: n,
|
|
|
|
}
|
2018-09-06 14:51:28 -07:00
|
|
|
}
|
2018-10-17 12:53:18 -07:00
|
|
|
|
|
|
|
// A pathKey is a representation of a location path suitable for use as a map key.
|
|
|
|
type pathKey struct {
|
|
|
|
s string
|
|
|
|
}
|
|
|
|
|
|
|
|
// newPathKey converts a location path to a pathKey.
|
2019-05-24 18:24:29 +09:00
|
|
|
func newPathKey(idxPath []int32) pathKey {
|
|
|
|
buf := make([]byte, 4*len(idxPath))
|
|
|
|
for i, x := range idxPath {
|
2018-10-17 12:53:18 -07:00
|
|
|
binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
|
|
|
|
}
|
|
|
|
return pathKey{string(buf)}
|
|
|
|
}
|
compiler/protogen, cmd/protoc-gen-go: use alternative comments API
This is a breaking change. High-level protogen API changes:
* remove GeneratedFile.PrintLeadingComments method
* add {Message,Field,Oneof,Enum,EnumValue,Service,Method}.Comments field
* add CommentSet and Comments type
CL/183157 added protoreflect.SourceLocations and it was discovered
that there can actually be duplicate locations for certain paths.
For that reason, we decided not to expose any helper methods
for looking up locations by path since it is unclear which location
to return if multiple matches.
The protogen.GeneratedFile.PrintLeadingComments has a similar dilemma
where it also needs to figure out what to do when duplicates exist.
Previously, it just chooses the first one with comments,
which may not be the right choice in a given context.
Analysis of current PrintLeadingComments usage shows that it is only
ever used (except once) for descriptor declarations.
In the case of descriptor declarations, they are guaranteed by protoc
to have only location.
Thus, we avoid the duplicate location problem by:
* Providing a CommentSet for every descriptor. The CommentSet contains
a set of leading and trailing comments of the Comments type.
* The Comments.String method knows how to interpret the comments
as provided by protoc and format them as // prefixed line comments.
* Values of the Comments type can be passed to the P method.
We drop direct support printing leading comments for non-descriptor locations,
but the exposure of the Comments type makes it easy for users to manually
handle other types of comments themselves.
Change-Id: Id4851456dc4e64d76bd6a30e8ad6137408dfb27a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/189198
Reviewed-by: Damien Neil <dneil@google.com>
2019-08-06 01:15:18 -07:00
|
|
|
|
|
|
|
// CommentSet is a set of leading and trailing comments associated
|
|
|
|
// with a .proto descriptor declaration.
|
|
|
|
type CommentSet struct {
|
|
|
|
LeadingDetached []Comments
|
|
|
|
Leading Comments
|
|
|
|
Trailing Comments
|
|
|
|
}
|
|
|
|
|
|
|
|
// Comments is a comments string as provided by protoc.
|
|
|
|
type Comments string
|
|
|
|
|
|
|
|
// String formats the comments by inserting // to the start of each line,
|
|
|
|
// ensuring that there is a trailing newline.
|
|
|
|
// An empty comment is formatted as an empty string.
|
|
|
|
func (c Comments) String() string {
|
|
|
|
if c == "" {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
var b []byte
|
|
|
|
for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
|
|
|
|
b = append(b, "//"...)
|
|
|
|
b = append(b, line...)
|
|
|
|
b = append(b, "\n"...)
|
|
|
|
}
|
|
|
|
return string(b)
|
|
|
|
}
|
2020-03-06 13:58:41 -08:00
|
|
|
|
|
|
|
var warnings = true
|
|
|
|
|
|
|
|
func warn(format string, a ...interface{}) {
|
|
|
|
if warnings {
|
|
|
|
log.Printf("WARNING: "+format, a...)
|
|
|
|
}
|
|
|
|
}
|