Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 1 | // Copyright 2018 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package protogen provides support for writing protoc plugins. |
| 6 | // |
Joe Tsai | 04f03cb | 2020-02-14 12:40:48 -0800 | [diff] [blame] | 7 | // Plugins for protoc, the Protocol Buffer compiler, |
| 8 | // are programs which read a CodeGeneratorRequest message from standard input |
| 9 | // and write a CodeGeneratorResponse message to standard output. |
| 10 | // This package provides support for writing plugins which generate Go code. |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 11 | package protogen |
| 12 | |
| 13 | import ( |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 14 | "bufio" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 15 | "bytes" |
Damien Neil | ba1159f | 2018-10-17 12:53:18 -0700 | [diff] [blame] | 16 | "encoding/binary" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 17 | "fmt" |
Damien Neil | 1ec3315 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 18 | "go/ast" |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 19 | "go/parser" |
| 20 | "go/printer" |
| 21 | "go/token" |
Joe Tsai | 124c812 | 2019-01-14 11:48:43 -0800 | [diff] [blame] | 22 | "go/types" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 23 | "io/ioutil" |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 24 | "log" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 25 | "os" |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 26 | "path" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 27 | "path/filepath" |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 28 | "sort" |
| 29 | "strconv" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 30 | "strings" |
| 31 | |
Damien Neil | 5c5b531 | 2019-05-14 12:44:37 -0700 | [diff] [blame] | 32 | "google.golang.org/protobuf/encoding/prototext" |
Damien Neil | e89e624 | 2019-05-13 23:55:40 -0700 | [diff] [blame] | 33 | "google.golang.org/protobuf/internal/fieldnum" |
Joe Tsai | 2e7817f | 2019-08-23 12:18:57 -0700 | [diff] [blame] | 34 | "google.golang.org/protobuf/internal/strs" |
Damien Neil | e89e624 | 2019-05-13 23:55:40 -0700 | [diff] [blame] | 35 | "google.golang.org/protobuf/proto" |
| 36 | "google.golang.org/protobuf/reflect/protodesc" |
| 37 | "google.golang.org/protobuf/reflect/protoreflect" |
| 38 | "google.golang.org/protobuf/reflect/protoregistry" |
Joe Tsai | e1f8d50 | 2018-11-26 18:55:29 -0800 | [diff] [blame] | 39 | |
Joe Tsai | a95b29f | 2019-05-16 12:47:20 -0700 | [diff] [blame] | 40 | "google.golang.org/protobuf/types/descriptorpb" |
| 41 | "google.golang.org/protobuf/types/pluginpb" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 42 | ) |
| 43 | |
Joe Tsai | 222a000 | 2020-02-24 11:21:30 -0800 | [diff] [blame] | 44 | const goPackageDocURL = "https://developers.google.com/protocol-buffers/docs/reference/go-generated#package" |
| 45 | |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 46 | // Run executes a function as a protoc plugin. |
| 47 | // |
| 48 | // It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin |
| 49 | // function, and writes a CodeGeneratorResponse message to os.Stdout. |
| 50 | // |
| 51 | // If a failure occurs while reading or writing, Run prints an error to |
| 52 | // os.Stderr and calls os.Exit(1). |
Joe Tsai | ab0ca4f | 2020-02-27 14:47:29 -0800 | [diff] [blame] | 53 | func (opts Options) Run(f func(*Plugin) error) { |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 54 | if err := run(opts, f); err != nil { |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 55 | fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err) |
| 56 | os.Exit(1) |
| 57 | } |
| 58 | } |
| 59 | |
Joe Tsai | ab0ca4f | 2020-02-27 14:47:29 -0800 | [diff] [blame] | 60 | func run(opts Options, f func(*Plugin) error) error { |
Damien Neil | d277b52 | 2018-10-04 15:30:51 -0700 | [diff] [blame] | 61 | if len(os.Args) > 1 { |
| 62 | return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1]) |
| 63 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 64 | in, err := ioutil.ReadAll(os.Stdin) |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | req := &pluginpb.CodeGeneratorRequest{} |
| 69 | if err := proto.Unmarshal(in, req); err != nil { |
| 70 | return err |
| 71 | } |
Joe Tsai | ab0ca4f | 2020-02-27 14:47:29 -0800 | [diff] [blame] | 72 | gen, err := opts.New(req) |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 73 | if err != nil { |
| 74 | return err |
| 75 | } |
| 76 | if err := f(gen); err != nil { |
| 77 | // Errors from the plugin function are reported by setting the |
| 78 | // error field in the CodeGeneratorResponse. |
| 79 | // |
| 80 | // In contrast, errors that indicate a problem in protoc |
| 81 | // itself (unparsable input, I/O errors, etc.) are reported |
| 82 | // to stderr. |
| 83 | gen.Error(err) |
| 84 | } |
| 85 | resp := gen.Response() |
| 86 | out, err := proto.Marshal(resp) |
| 87 | if err != nil { |
| 88 | return err |
| 89 | } |
| 90 | if _, err := os.Stdout.Write(out); err != nil { |
| 91 | return err |
| 92 | } |
| 93 | return nil |
| 94 | } |
| 95 | |
| 96 | // A Plugin is a protoc plugin invocation. |
| 97 | type Plugin struct { |
| 98 | // Request is the CodeGeneratorRequest provided by protoc. |
| 99 | Request *pluginpb.CodeGeneratorRequest |
| 100 | |
| 101 | // Files is the set of files to generate and everything they import. |
| 102 | // Files appear in topological order, so each file appears before any |
| 103 | // file that imports it. |
| 104 | Files []*File |
Joe Tsai | 2cec484 | 2019-08-20 20:14:19 -0700 | [diff] [blame] | 105 | FilesByPath map[string]*File |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 106 | |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 107 | fileReg *protoregistry.Files |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 108 | enumsByName map[protoreflect.FullName]*Enum |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 109 | messagesByName map[protoreflect.FullName]*Message |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 110 | annotateCode bool |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 111 | pathType pathType |
Damien Neil | ffbc5fd | 2020-02-12 23:38:30 -0800 | [diff] [blame] | 112 | module string |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 113 | genFiles []*GeneratedFile |
Joe Tsai | ab0ca4f | 2020-02-27 14:47:29 -0800 | [diff] [blame] | 114 | opts Options |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 115 | err error |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 116 | } |
| 117 | |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 118 | type Options struct { |
| 119 | // If ParamFunc is non-nil, it will be called with each unknown |
| 120 | // generator parameter. |
| 121 | // |
| 122 | // Plugins for protoc can accept parameters from the command line, |
| 123 | // passed in the --<lang>_out protoc, separated from the output |
| 124 | // directory with a colon; e.g., |
| 125 | // |
| 126 | // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory> |
| 127 | // |
| 128 | // Parameters passed in this fashion as a comma-separated list of |
| 129 | // key=value pairs will be passed to the ParamFunc. |
| 130 | // |
| 131 | // The (flag.FlagSet).Set method matches this function signature, |
| 132 | // so parameters can be converted into flags as in the following: |
| 133 | // |
| 134 | // var flags flag.FlagSet |
| 135 | // value := flags.Bool("param", false, "") |
| 136 | // opts := &protogen.Options{ |
| 137 | // ParamFunc: flags.Set, |
| 138 | // } |
| 139 | // protogen.Run(opts, func(p *protogen.Plugin) error { |
| 140 | // if *value { ... } |
| 141 | // }) |
| 142 | ParamFunc func(name, value string) error |
Damien Neil | 1fa8ab0 | 2018-09-27 15:51:05 -0700 | [diff] [blame] | 143 | |
| 144 | // ImportRewriteFunc is called with the import path of each package |
| 145 | // imported by a generated file. It returns the import path to use |
| 146 | // for this package. |
| 147 | ImportRewriteFunc func(GoImportPath) GoImportPath |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 148 | } |
| 149 | |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 150 | // New returns a new Plugin. |
Joe Tsai | ab0ca4f | 2020-02-27 14:47:29 -0800 | [diff] [blame] | 151 | func (opts Options) New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) { |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 152 | gen := &Plugin{ |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 153 | Request: req, |
Joe Tsai | 2cec484 | 2019-08-20 20:14:19 -0700 | [diff] [blame] | 154 | FilesByPath: make(map[string]*File), |
Damien Neil | c826885 | 2019-10-08 13:28:53 -0700 | [diff] [blame] | 155 | fileReg: new(protoregistry.Files), |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 156 | enumsByName: make(map[protoreflect.FullName]*Enum), |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 157 | messagesByName: make(map[protoreflect.FullName]*Message), |
Damien Neil | 1fa8ab0 | 2018-09-27 15:51:05 -0700 | [diff] [blame] | 158 | opts: opts, |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 159 | } |
| 160 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 161 | packageNames := make(map[string]GoPackageName) // filename -> package name |
| 162 | importPaths := make(map[string]GoImportPath) // filename -> import path |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 163 | mfiles := make(map[string]bool) // filename set |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 164 | var packageImportPath GoImportPath |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 165 | for _, param := range strings.Split(req.GetParameter(), ",") { |
| 166 | var value string |
| 167 | if i := strings.Index(param, "="); i >= 0 { |
| 168 | value = param[i+1:] |
| 169 | param = param[0:i] |
| 170 | } |
| 171 | switch param { |
| 172 | case "": |
| 173 | // Ignore. |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 174 | case "import_path": |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 175 | packageImportPath = GoImportPath(value) |
Damien Neil | ffbc5fd | 2020-02-12 23:38:30 -0800 | [diff] [blame] | 176 | case "module": |
| 177 | gen.module = value |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 178 | case "paths": |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 179 | switch value { |
| 180 | case "import": |
| 181 | gen.pathType = pathTypeImport |
| 182 | case "source_relative": |
| 183 | gen.pathType = pathTypeSourceRelative |
| 184 | default: |
| 185 | return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value) |
| 186 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 187 | case "annotate_code": |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 188 | switch value { |
| 189 | case "true", "": |
| 190 | gen.annotateCode = true |
| 191 | case "false": |
| 192 | default: |
| 193 | return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param) |
| 194 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 195 | default: |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 196 | if param[0] == 'M' { |
Joe Tsai | 6ad8e63 | 2020-03-18 00:59:09 -0700 | [diff] [blame] | 197 | if i := strings.Index(value, ";"); i >= 0 { |
| 198 | pkgName := GoPackageName(value[i+1:]) |
| 199 | if otherName, ok := packageNames[param[1:]]; ok && pkgName != otherName { |
| 200 | return nil, fmt.Errorf("inconsistent package names for %q: %q != %q", value[:i], pkgName, otherName) |
| 201 | } |
| 202 | packageNames[param[1:]] = pkgName |
| 203 | value = value[:i] |
| 204 | } |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 205 | importPaths[param[1:]] = GoImportPath(value) |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 206 | mfiles[param[1:]] = true |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 207 | continue |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 208 | } |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 209 | if opts.ParamFunc != nil { |
| 210 | if err := opts.ParamFunc(param, value); err != nil { |
| 211 | return nil, err |
| 212 | } |
| 213 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 214 | } |
| 215 | } |
Damien Neil | ffbc5fd | 2020-02-12 23:38:30 -0800 | [diff] [blame] | 216 | if gen.module != "" { |
| 217 | // When the module= option is provided, we strip the module name |
| 218 | // prefix from generated files. This only makes sense if generated |
| 219 | // filenames are based on the import path, so default to paths=import |
| 220 | // and complain if source_relative was selected manually. |
| 221 | switch gen.pathType { |
| 222 | case pathTypeLegacy: |
| 223 | gen.pathType = pathTypeImport |
| 224 | case pathTypeSourceRelative: |
| 225 | return nil, fmt.Errorf("cannot use module= with paths=source_relative") |
| 226 | } |
| 227 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 228 | |
| 229 | // Figure out the import path and package name for each file. |
| 230 | // |
| 231 | // The rules here are complicated and have grown organically over time. |
| 232 | // Interactions between different ways of specifying package information |
| 233 | // may be surprising. |
| 234 | // |
| 235 | // The recommended approach is to include a go_package option in every |
| 236 | // .proto source file specifying the full import path of the Go package |
| 237 | // associated with this file. |
| 238 | // |
Joe Tsai | 8d30bbe | 2019-05-16 15:53:25 -0700 | [diff] [blame] | 239 | // option go_package = "google.golang.org/protobuf/types/known/anypb"; |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 240 | // |
| 241 | // Build systems which want to exert full control over import paths may |
| 242 | // specify M<filename>=<import_path> flags. |
| 243 | // |
| 244 | // Other approaches are not recommend. |
| 245 | generatedFileNames := make(map[string]bool) |
| 246 | for _, name := range gen.Request.FileToGenerate { |
| 247 | generatedFileNames[name] = true |
| 248 | } |
| 249 | // We need to determine the import paths before the package names, |
| 250 | // because the Go package name for a file is sometimes derived from |
| 251 | // different file in the same package. |
| 252 | packageNameForImportPath := make(map[GoImportPath]GoPackageName) |
| 253 | for _, fdesc := range gen.Request.ProtoFile { |
| 254 | filename := fdesc.GetName() |
| 255 | packageName, importPath := goPackageOption(fdesc) |
| 256 | switch { |
| 257 | case importPaths[filename] != "": |
Damien Neil | aadba56 | 2020-02-15 14:28:51 -0800 | [diff] [blame] | 258 | // Command line: Mfoo.proto=quux/bar |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 259 | // |
| 260 | // Explicit mapping of source file to import path. |
| 261 | case generatedFileNames[filename] && packageImportPath != "": |
| 262 | // Command line: import_path=quux/bar |
| 263 | // |
| 264 | // The import_path flag sets the import path for every file that |
| 265 | // we generate code for. |
| 266 | importPaths[filename] = packageImportPath |
| 267 | case importPath != "": |
| 268 | // Source file: option go_package = "quux/bar"; |
| 269 | // |
| 270 | // The go_package option sets the import path. Most users should use this. |
| 271 | importPaths[filename] = importPath |
| 272 | default: |
| 273 | // Source filename. |
| 274 | // |
| 275 | // Last resort when nothing else is available. |
| 276 | importPaths[filename] = GoImportPath(path.Dir(filename)) |
| 277 | } |
| 278 | if packageName != "" { |
| 279 | packageNameForImportPath[importPaths[filename]] = packageName |
| 280 | } |
| 281 | } |
| 282 | for _, fdesc := range gen.Request.ProtoFile { |
| 283 | filename := fdesc.GetName() |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 284 | packageName, importPath := goPackageOption(fdesc) |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 285 | defaultPackageName := packageNameForImportPath[importPaths[filename]] |
| 286 | switch { |
Joe Tsai | 6ad8e63 | 2020-03-18 00:59:09 -0700 | [diff] [blame] | 287 | case packageNames[filename] != "": |
| 288 | // A package name specified by the "M" command-line argument. |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 289 | case packageName != "": |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 290 | // TODO: For the "M" command-line argument, this means that the |
| 291 | // package name can be derived from the go_package option. |
| 292 | // Go package information should either consistently come from the |
| 293 | // command-line or the .proto source file, but not both. |
| 294 | // See how to make this consistent. |
| 295 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 296 | // Source file: option go_package = "quux/bar"; |
| 297 | packageNames[filename] = packageName |
| 298 | case defaultPackageName != "": |
| 299 | // A go_package option in another file in the same package. |
| 300 | // |
| 301 | // This is a poor choice in general, since every source file should |
| 302 | // contain a go_package option. Supported mainly for historical |
| 303 | // compatibility. |
| 304 | packageNames[filename] = defaultPackageName |
| 305 | case generatedFileNames[filename] && packageImportPath != "": |
| 306 | // Command line: import_path=quux/bar |
| 307 | packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath))) |
| 308 | case fdesc.GetPackage() != "": |
| 309 | // Source file: package quux.bar; |
| 310 | packageNames[filename] = cleanPackageName(fdesc.GetPackage()) |
| 311 | default: |
| 312 | // Source filename. |
| 313 | packageNames[filename] = cleanPackageName(baseName(filename)) |
| 314 | } |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 315 | |
| 316 | goPkgOpt := string(importPaths[filename]) |
| 317 | if path.Base(string(goPkgOpt)) != string(packageNames[filename]) { |
| 318 | goPkgOpt += ";" + string(packageNames[filename]) |
| 319 | } |
| 320 | switch { |
| 321 | case packageImportPath != "": |
| 322 | // Command line: import_path=quux/bar |
Damien Neil | e358d43 | 2020-03-06 13:58:41 -0800 | [diff] [blame] | 323 | warn("Deprecated use of the 'import_path' command-line argument. In %q, please specify:\n"+ |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 324 | "\toption go_package = %q;\n"+ |
| 325 | "A future release of protoc-gen-go will no longer support the 'import_path' argument.\n"+ |
Joe Tsai | 222a000 | 2020-02-24 11:21:30 -0800 | [diff] [blame] | 326 | "See "+goPackageDocURL+" for more information.\n"+ |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 327 | "\n", fdesc.GetName(), goPkgOpt) |
| 328 | case mfiles[filename]: |
| 329 | // Command line: M=foo.proto=quux/bar |
| 330 | case packageName != "" && importPath == "": |
| 331 | // Source file: option go_package = "quux"; |
Damien Neil | e358d43 | 2020-03-06 13:58:41 -0800 | [diff] [blame] | 332 | warn("Deprecated use of 'go_package' option without a full import path in %q, please specify:\n"+ |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 333 | "\toption go_package = %q;\n"+ |
| 334 | "A future release of protoc-gen-go will require the import path be specified.\n"+ |
Joe Tsai | 222a000 | 2020-02-24 11:21:30 -0800 | [diff] [blame] | 335 | "See "+goPackageDocURL+" for more information.\n"+ |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 336 | "\n", fdesc.GetName(), goPkgOpt) |
| 337 | case packageName == "" && importPath == "": |
| 338 | // No Go package information provided. |
Damien Neil | e358d43 | 2020-03-06 13:58:41 -0800 | [diff] [blame] | 339 | warn("Missing 'go_package' option in %q, please specify:\n"+ |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 340 | "\toption go_package = %q;\n"+ |
| 341 | "A future release of protoc-gen-go will require this be specified.\n"+ |
Joe Tsai | 222a000 | 2020-02-24 11:21:30 -0800 | [diff] [blame] | 342 | "See "+goPackageDocURL+" for more information.\n"+ |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 343 | "\n", fdesc.GetName(), goPkgOpt) |
| 344 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 345 | } |
| 346 | |
| 347 | // Consistency check: Every file with the same Go import path should have |
| 348 | // the same Go package name. |
| 349 | packageFiles := make(map[GoImportPath][]string) |
| 350 | for filename, importPath := range importPaths { |
Damien Neil | bbbd38f | 2018-10-08 16:36:49 -0700 | [diff] [blame] | 351 | if _, ok := packageNames[filename]; !ok { |
| 352 | // Skip files mentioned in a M<file>=<import_path> parameter |
| 353 | // but which do not appear in the CodeGeneratorRequest. |
| 354 | continue |
| 355 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 356 | packageFiles[importPath] = append(packageFiles[importPath], filename) |
| 357 | } |
| 358 | for importPath, filenames := range packageFiles { |
| 359 | for i := 1; i < len(filenames); i++ { |
| 360 | if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b { |
| 361 | return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)", |
| 362 | importPath, a, filenames[0], b, filenames[i]) |
| 363 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 364 | } |
| 365 | } |
| 366 | |
| 367 | for _, fdesc := range gen.Request.ProtoFile { |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 368 | filename := fdesc.GetName() |
Joe Tsai | 2cec484 | 2019-08-20 20:14:19 -0700 | [diff] [blame] | 369 | if gen.FilesByPath[filename] != nil { |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 370 | return nil, fmt.Errorf("duplicate file name: %q", filename) |
| 371 | } |
| 372 | f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename]) |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 373 | if err != nil { |
| 374 | return nil, err |
| 375 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 376 | gen.Files = append(gen.Files, f) |
Joe Tsai | 2cec484 | 2019-08-20 20:14:19 -0700 | [diff] [blame] | 377 | gen.FilesByPath[filename] = f |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 378 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 379 | for _, filename := range gen.Request.FileToGenerate { |
Joe Tsai | 2cec484 | 2019-08-20 20:14:19 -0700 | [diff] [blame] | 380 | f, ok := gen.FilesByPath[filename] |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 381 | if !ok { |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 382 | return nil, fmt.Errorf("no descriptor for generated file: %v", filename) |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 383 | } |
| 384 | f.Generate = true |
| 385 | } |
| 386 | return gen, nil |
| 387 | } |
| 388 | |
| 389 | // Error records an error in code generation. The generator will report the |
| 390 | // error back to protoc and will not produce output. |
| 391 | func (gen *Plugin) Error(err error) { |
| 392 | if gen.err == nil { |
| 393 | gen.err = err |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | // Response returns the generator output. |
| 398 | func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse { |
| 399 | resp := &pluginpb.CodeGeneratorResponse{} |
| 400 | if gen.err != nil { |
Damien Neil | a8a2cea | 2019-07-10 16:17:16 -0700 | [diff] [blame] | 401 | resp.Error = proto.String(gen.err.Error()) |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 402 | return resp |
| 403 | } |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 404 | for _, g := range gen.genFiles { |
Damien Neil | 7bf3ce2 | 2018-12-21 15:54:06 -0800 | [diff] [blame] | 405 | if g.skip { |
| 406 | continue |
| 407 | } |
| 408 | content, err := g.Content() |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 409 | if err != nil { |
| 410 | return &pluginpb.CodeGeneratorResponse{ |
Damien Neil | a8a2cea | 2019-07-10 16:17:16 -0700 | [diff] [blame] | 411 | Error: proto.String(err.Error()), |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 412 | } |
| 413 | } |
Damien Neil | ffbc5fd | 2020-02-12 23:38:30 -0800 | [diff] [blame] | 414 | filename := g.filename |
| 415 | if gen.module != "" { |
| 416 | trim := gen.module + "/" |
| 417 | if !strings.HasPrefix(filename, trim) { |
| 418 | return &pluginpb.CodeGeneratorResponse{ |
| 419 | Error: proto.String(fmt.Sprintf("%v: generated file does not match prefix %q", filename, gen.module)), |
| 420 | } |
| 421 | } |
| 422 | filename = strings.TrimPrefix(filename, trim) |
| 423 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 424 | resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{ |
Damien Neil | ffbc5fd | 2020-02-12 23:38:30 -0800 | [diff] [blame] | 425 | Name: proto.String(filename), |
Damien Neil | a8a2cea | 2019-07-10 16:17:16 -0700 | [diff] [blame] | 426 | Content: proto.String(string(content)), |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 427 | }) |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 428 | if gen.annotateCode && strings.HasSuffix(g.filename, ".go") { |
| 429 | meta, err := g.metaFile(content) |
| 430 | if err != nil { |
| 431 | return &pluginpb.CodeGeneratorResponse{ |
Damien Neil | a8a2cea | 2019-07-10 16:17:16 -0700 | [diff] [blame] | 432 | Error: proto.String(err.Error()), |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 433 | } |
| 434 | } |
| 435 | resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{ |
Damien Neil | ffbc5fd | 2020-02-12 23:38:30 -0800 | [diff] [blame] | 436 | Name: proto.String(filename + ".meta"), |
Damien Neil | a8a2cea | 2019-07-10 16:17:16 -0700 | [diff] [blame] | 437 | Content: proto.String(meta), |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 438 | }) |
| 439 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 440 | } |
| 441 | return resp |
| 442 | } |
| 443 | |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 444 | // A File describes a .proto source file. |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 445 | type File struct { |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 446 | Desc protoreflect.FileDescriptor |
Joe Tsai | e1f8d50 | 2018-11-26 18:55:29 -0800 | [diff] [blame] | 447 | Proto *descriptorpb.FileDescriptorProto |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 448 | |
Joe Tsai | b6405bd | 2018-11-15 14:44:37 -0800 | [diff] [blame] | 449 | GoDescriptorIdent GoIdent // name of Go variable for the file descriptor |
| 450 | GoPackageName GoPackageName // name of this file's Go package |
| 451 | GoImportPath GoImportPath // import path of this file's Go package |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 452 | |
| 453 | Enums []*Enum // top-level enum declarations |
| 454 | Messages []*Message // top-level message declarations |
| 455 | Extensions []*Extension // top-level extension declarations |
| 456 | Services []*Service // top-level service declarations |
| 457 | |
| 458 | Generate bool // true if we should generate code for this file |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 459 | |
| 460 | // GeneratedFilenamePrefix is used to construct filenames for generated |
| 461 | // files associated with this source file. |
| 462 | // |
| 463 | // For example, the source file "dir/foo.proto" might have a filename prefix |
| 464 | // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go". |
| 465 | GeneratedFilenamePrefix string |
Damien Neil | ba1159f | 2018-10-17 12:53:18 -0700 | [diff] [blame] | 466 | |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 467 | comments map[pathKey]CommentSet |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 468 | } |
| 469 | |
Joe Tsai | e1f8d50 | 2018-11-26 18:55:29 -0800 | [diff] [blame] | 470 | func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) { |
| 471 | desc, err := protodesc.NewFile(p, gen.fileReg) |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 472 | if err != nil { |
| 473 | return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err) |
| 474 | } |
Damien Neil | c826885 | 2019-10-08 13:28:53 -0700 | [diff] [blame] | 475 | if err := gen.fileReg.RegisterFile(desc); err != nil { |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 476 | return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err) |
| 477 | } |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 478 | f := &File{ |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 479 | Desc: desc, |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 480 | Proto: p, |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 481 | GoPackageName: packageName, |
| 482 | GoImportPath: importPath, |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 483 | comments: make(map[pathKey]CommentSet), |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 484 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 485 | |
| 486 | // Determine the prefix for generated Go files. |
| 487 | prefix := p.GetName() |
| 488 | if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" { |
| 489 | prefix = prefix[:len(prefix)-len(ext)] |
| 490 | } |
Damien Neil | aadba56 | 2020-02-15 14:28:51 -0800 | [diff] [blame] | 491 | switch gen.pathType { |
| 492 | case pathTypeLegacy: |
| 493 | // The default is to derive the output filename from the Go import path |
| 494 | // if the file contains a go_package option,or from the input filename instead. |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 495 | if _, importPath := goPackageOption(p); importPath != "" { |
| 496 | prefix = path.Join(string(importPath), path.Base(prefix)) |
| 497 | } |
Damien Neil | aadba56 | 2020-02-15 14:28:51 -0800 | [diff] [blame] | 498 | case pathTypeImport: |
| 499 | // If paths=import, the output filename is derived from the Go import path. |
| 500 | prefix = path.Join(string(f.GoImportPath), path.Base(prefix)) |
| 501 | case pathTypeSourceRelative: |
| 502 | // If paths=source_relative, the output filename is derived from |
| 503 | // the input filename. |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 504 | } |
Joe Tsai | b6405bd | 2018-11-15 14:44:37 -0800 | [diff] [blame] | 505 | f.GoDescriptorIdent = GoIdent{ |
Joe Tsai | 2e7817f | 2019-08-23 12:18:57 -0700 | [diff] [blame] | 506 | GoName: "File_" + strs.GoSanitized(p.GetName()), |
Joe Tsai | b6405bd | 2018-11-15 14:44:37 -0800 | [diff] [blame] | 507 | GoImportPath: f.GoImportPath, |
| 508 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 509 | f.GeneratedFilenamePrefix = prefix |
| 510 | |
Damien Neil | ba1159f | 2018-10-17 12:53:18 -0700 | [diff] [blame] | 511 | for _, loc := range p.GetSourceCodeInfo().GetLocation() { |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 512 | // Descriptors declarations are guaranteed to have unique comment sets. |
| 513 | // Other locations may not be unique, but we don't use them. |
| 514 | var leadingDetached []Comments |
| 515 | for _, s := range loc.GetLeadingDetachedComments() { |
| 516 | leadingDetached = append(leadingDetached, Comments(s)) |
| 517 | } |
| 518 | f.comments[newPathKey(loc.Path)] = CommentSet{ |
| 519 | LeadingDetached: leadingDetached, |
| 520 | Leading: Comments(loc.GetLeadingComments()), |
| 521 | Trailing: Comments(loc.GetTrailingComments()), |
| 522 | } |
Damien Neil | ba1159f | 2018-10-17 12:53:18 -0700 | [diff] [blame] | 523 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 524 | for i, eds := 0, desc.Enums(); i < eds.Len(); i++ { |
| 525 | f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i))) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 526 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 527 | for i, mds := 0, desc.Messages(); i < mds.Len(); i++ { |
| 528 | f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i))) |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 529 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 530 | for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ { |
| 531 | f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i))) |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 532 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 533 | for i, sds := 0, desc.Services(); i < sds.Len(); i++ { |
| 534 | f.Services = append(f.Services, newService(gen, f, sds.Get(i))) |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 535 | } |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 536 | for _, message := range f.Messages { |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 537 | if err := message.resolveDependencies(gen); err != nil { |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 538 | return nil, err |
| 539 | } |
| 540 | } |
| 541 | for _, extension := range f.Extensions { |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 542 | if err := extension.resolveDependencies(gen); err != nil { |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 543 | return nil, err |
| 544 | } |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 545 | } |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 546 | for _, service := range f.Services { |
| 547 | for _, method := range service.Methods { |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 548 | if err := method.resolveDependencies(gen); err != nil { |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 549 | return nil, err |
| 550 | } |
| 551 | } |
| 552 | } |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 553 | return f, nil |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 554 | } |
| 555 | |
Koichi Shiraishi | ea2076d | 2019-05-24 18:24:29 +0900 | [diff] [blame] | 556 | func (f *File) location(idxPath ...int32) Location { |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 557 | return Location{ |
| 558 | SourceFile: f.Desc.Path(), |
Koichi Shiraishi | ea2076d | 2019-05-24 18:24:29 +0900 | [diff] [blame] | 559 | Path: idxPath, |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 560 | } |
| 561 | } |
| 562 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 563 | // goPackageOption interprets a file's go_package option. |
| 564 | // If there is no go_package, it returns ("", ""). |
| 565 | // If there's a simple name, it returns (pkg, ""). |
| 566 | // If the option implies an import path, it returns (pkg, impPath). |
Joe Tsai | e1f8d50 | 2018-11-26 18:55:29 -0800 | [diff] [blame] | 567 | func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) { |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 568 | opt := d.GetOptions().GetGoPackage() |
| 569 | if opt == "" { |
| 570 | return "", "" |
| 571 | } |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 572 | rawPkg, impPath := goPackageOptionRaw(opt) |
| 573 | pkg = cleanPackageName(rawPkg) |
| 574 | if string(pkg) != rawPkg && impPath != "" { |
Damien Neil | e358d43 | 2020-03-06 13:58:41 -0800 | [diff] [blame] | 575 | warn("Malformed 'go_package' option in %q, please specify:\n"+ |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 576 | "\toption go_package = %q;\n"+ |
| 577 | "A future release of protoc-gen-go will reject this.\n"+ |
Joe Tsai | 222a000 | 2020-02-24 11:21:30 -0800 | [diff] [blame] | 578 | "See "+goPackageDocURL+" for more information.\n"+ |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 579 | "\n", d.GetName(), string(impPath)+";"+string(pkg)) |
| 580 | } |
| 581 | return pkg, impPath |
| 582 | } |
| 583 | func goPackageOptionRaw(opt string) (rawPkg string, impPath GoImportPath) { |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 584 | // A semicolon-delimited suffix delimits the import path and package name. |
| 585 | if i := strings.Index(opt, ";"); i >= 0 { |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 586 | return opt[i+1:], GoImportPath(opt[:i]) |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 587 | } |
| 588 | // The presence of a slash implies there's an import path. |
| 589 | if i := strings.LastIndex(opt, "/"); i >= 0 { |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 590 | return opt[i+1:], GoImportPath(opt) |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 591 | } |
Joe Tsai | 3e80249 | 2019-09-07 13:06:27 -0700 | [diff] [blame] | 592 | return opt, "" |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 593 | } |
| 594 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 595 | // An Enum describes an enum. |
| 596 | type Enum struct { |
| 597 | Desc protoreflect.EnumDescriptor |
| 598 | |
| 599 | GoIdent GoIdent // name of the generated Go type |
| 600 | |
| 601 | Values []*EnumValue // enum value declarations |
| 602 | |
| 603 | Location Location // location of this enum |
| 604 | Comments CommentSet // comments associated with this enum |
| 605 | } |
| 606 | |
| 607 | func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum { |
| 608 | var loc Location |
| 609 | if parent != nil { |
| 610 | loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index())) |
| 611 | } else { |
| 612 | loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index())) |
| 613 | } |
| 614 | enum := &Enum{ |
| 615 | Desc: desc, |
| 616 | GoIdent: newGoIdent(f, desc), |
| 617 | Location: loc, |
| 618 | Comments: f.comments[newPathKey(loc.Path)], |
| 619 | } |
| 620 | gen.enumsByName[desc.FullName()] = enum |
| 621 | for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ { |
| 622 | enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i))) |
| 623 | } |
| 624 | return enum |
| 625 | } |
| 626 | |
| 627 | // An EnumValue describes an enum value. |
| 628 | type EnumValue struct { |
| 629 | Desc protoreflect.EnumValueDescriptor |
| 630 | |
| 631 | GoIdent GoIdent // name of the generated Go declaration |
| 632 | |
Joe Tsai | 4df99fd | 2019-08-20 22:26:16 -0700 | [diff] [blame] | 633 | Parent *Enum // enum in which this value is declared |
| 634 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 635 | Location Location // location of this enum value |
| 636 | Comments CommentSet // comments associated with this enum value |
| 637 | } |
| 638 | |
| 639 | func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue { |
| 640 | // A top-level enum value's name is: EnumName_ValueName |
| 641 | // An enum value contained in a message is: MessageName_ValueName |
| 642 | // |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 643 | // For historical reasons, enum value names are not camel-cased. |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 644 | parentIdent := enum.GoIdent |
| 645 | if message != nil { |
| 646 | parentIdent = message.GoIdent |
| 647 | } |
| 648 | name := parentIdent.GoName + "_" + string(desc.Name()) |
| 649 | loc := enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index())) |
| 650 | return &EnumValue{ |
| 651 | Desc: desc, |
| 652 | GoIdent: f.GoImportPath.Ident(name), |
Joe Tsai | 4df99fd | 2019-08-20 22:26:16 -0700 | [diff] [blame] | 653 | Parent: enum, |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 654 | Location: loc, |
| 655 | Comments: f.comments[newPathKey(loc.Path)], |
| 656 | } |
| 657 | } |
| 658 | |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 659 | // A Message describes a message. |
| 660 | type Message struct { |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 661 | Desc protoreflect.MessageDescriptor |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 662 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 663 | GoIdent GoIdent // name of the generated Go type |
| 664 | |
| 665 | Fields []*Field // message field declarations |
| 666 | Oneofs []*Oneof // message oneof declarations |
| 667 | |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 668 | Enums []*Enum // nested enum declarations |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 669 | Messages []*Message // nested message declarations |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 670 | Extensions []*Extension // nested extension declarations |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 671 | |
| 672 | Location Location // location of this message |
| 673 | Comments CommentSet // comments associated with this message |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 674 | } |
| 675 | |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 676 | func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message { |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 677 | var loc Location |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 678 | if parent != nil { |
Joe Tsai | ca46d8c | 2019-03-20 16:51:09 -0700 | [diff] [blame] | 679 | loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index())) |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 680 | } else { |
Joe Tsai | ca46d8c | 2019-03-20 16:51:09 -0700 | [diff] [blame] | 681 | loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index())) |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 682 | } |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 683 | message := &Message{ |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 684 | Desc: desc, |
| 685 | GoIdent: newGoIdent(f, desc), |
| 686 | Location: loc, |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 687 | Comments: f.comments[newPathKey(loc.Path)], |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 688 | } |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 689 | gen.messagesByName[desc.FullName()] = message |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 690 | for i, eds := 0, desc.Enums(); i < eds.Len(); i++ { |
| 691 | message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i))) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 692 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 693 | for i, mds := 0, desc.Messages(); i < mds.Len(); i++ { |
| 694 | message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i))) |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 695 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 696 | for i, fds := 0, desc.Fields(); i < fds.Len(); i++ { |
| 697 | message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i))) |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 698 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 699 | for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ { |
| 700 | message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i))) |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 701 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 702 | for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ { |
| 703 | message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i))) |
| 704 | } |
| 705 | |
| 706 | // Resolve local references between fields and oneofs. |
| 707 | for _, field := range message.Fields { |
| 708 | if od := field.Desc.ContainingOneof(); od != nil { |
| 709 | oneof := message.Oneofs[od.Index()] |
| 710 | field.Oneof = oneof |
| 711 | oneof.Fields = append(oneof.Fields, field) |
| 712 | } |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 713 | } |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 714 | |
| 715 | // Field name conflict resolution. |
| 716 | // |
| 717 | // We assume well-known method names that may be attached to a generated |
| 718 | // message type, as well as a 'Get*' method for each field. For each |
| 719 | // field in turn, we add _s to its name until there are no conflicts. |
| 720 | // |
| 721 | // Any change to the following set of method names is a potential |
| 722 | // incompatible API change because it may change generated field names. |
| 723 | // |
| 724 | // TODO: If we ever support a 'go_name' option to set the Go name of a |
| 725 | // field, we should consider dropping this entirely. The conflict |
| 726 | // resolution algorithm is subtle and surprising (changing the order |
| 727 | // in which fields appear in the .proto source file can change the |
| 728 | // names of fields in generated code), and does not adapt well to |
| 729 | // adding new per-field methods such as setters. |
| 730 | usedNames := map[string]bool{ |
| 731 | "Reset": true, |
| 732 | "String": true, |
| 733 | "ProtoMessage": true, |
| 734 | "Marshal": true, |
| 735 | "Unmarshal": true, |
| 736 | "ExtensionRangeArray": true, |
| 737 | "ExtensionMap": true, |
| 738 | "Descriptor": true, |
| 739 | } |
Joe Tsai | d6966a4 | 2019-01-08 10:59:34 -0800 | [diff] [blame] | 740 | makeNameUnique := func(name string, hasGetter bool) string { |
| 741 | for usedNames[name] || (hasGetter && usedNames["Get"+name]) { |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 742 | name += "_" |
| 743 | } |
| 744 | usedNames[name] = true |
Joe Tsai | d6966a4 | 2019-01-08 10:59:34 -0800 | [diff] [blame] | 745 | usedNames["Get"+name] = hasGetter |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 746 | return name |
| 747 | } |
| 748 | for _, field := range message.Fields { |
Joe Tsai | d6966a4 | 2019-01-08 10:59:34 -0800 | [diff] [blame] | 749 | field.GoName = makeNameUnique(field.GoName, true) |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 750 | field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName |
| 751 | if field.Oneof != nil && field.Oneof.Fields[0] == field { |
| 752 | // Make the name for a oneof unique as well. For historical reasons, |
| 753 | // this assumes that a getter method is not generated for oneofs. |
| 754 | // This is incorrect, but fixing it breaks existing code. |
| 755 | field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false) |
| 756 | field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | // Oneof field name conflict resolution. |
| 761 | // |
| 762 | // This conflict resolution is incomplete as it does not consider collisions |
| 763 | // with other oneof field types, but fixing it breaks existing code. |
| 764 | for _, field := range message.Fields { |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 765 | if field.Oneof != nil { |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 766 | Loop: |
| 767 | for { |
| 768 | for _, nestedMessage := range message.Messages { |
| 769 | if nestedMessage.GoIdent == field.GoIdent { |
| 770 | field.GoIdent.GoName += "_" |
| 771 | continue Loop |
| 772 | } |
| 773 | } |
| 774 | for _, nestedEnum := range message.Enums { |
| 775 | if nestedEnum.GoIdent == field.GoIdent { |
| 776 | field.GoIdent.GoName += "_" |
| 777 | continue Loop |
| 778 | } |
| 779 | } |
| 780 | break Loop |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 781 | } |
| 782 | } |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 783 | } |
| 784 | |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 785 | return message |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 786 | } |
| 787 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 788 | func (message *Message) resolveDependencies(gen *Plugin) error { |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 789 | for _, field := range message.Fields { |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 790 | if err := field.resolveDependencies(gen); err != nil { |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 791 | return err |
| 792 | } |
| 793 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 794 | for _, message := range message.Messages { |
| 795 | if err := message.resolveDependencies(gen); err != nil { |
| 796 | return err |
| 797 | } |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 798 | } |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 799 | for _, extension := range message.Extensions { |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 800 | if err := extension.resolveDependencies(gen); err != nil { |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 801 | return err |
| 802 | } |
| 803 | } |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 804 | return nil |
| 805 | } |
| 806 | |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 807 | // A Field describes a message field. |
| 808 | type Field struct { |
| 809 | Desc protoreflect.FieldDescriptor |
| 810 | |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 811 | // GoName is the base name of this field's Go field and methods. |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 812 | // For code generated by protoc-gen-go, this means a field named |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 813 | // '{{GoName}}' and a getter method named 'Get{{GoName}}'. |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 814 | GoName string // e.g., "FieldName" |
| 815 | |
| 816 | // GoIdent is the base name of a top-level declaration for this field. |
| 817 | // For code generated by protoc-gen-go, this means a wrapper type named |
| 818 | // '{{GoIdent}}' for members fields of a oneof, and a variable named |
| 819 | // 'E_{{GoIdent}}' for extension fields. |
| 820 | GoIdent GoIdent // e.g., "MessageName_FieldName" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 821 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 822 | Parent *Message // message in which this field is declared; nil if top-level extension |
| 823 | Oneof *Oneof // containing oneof; nil if not part of a oneof |
| 824 | Extendee *Message // extended message for extension fields; nil otherwise |
| 825 | |
| 826 | Enum *Enum // type for enum fields; nil otherwise |
| 827 | Message *Message // type for message or group fields; nil otherwise |
| 828 | |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 829 | Location Location // location of this field |
| 830 | Comments CommentSet // comments associated with this field |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 831 | } |
| 832 | |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 833 | func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field { |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 834 | var loc Location |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 835 | switch { |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 836 | case desc.IsExtension() && message == nil: |
Joe Tsai | ca46d8c | 2019-03-20 16:51:09 -0700 | [diff] [blame] | 837 | loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index())) |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 838 | case desc.IsExtension() && message != nil: |
Joe Tsai | ca46d8c | 2019-03-20 16:51:09 -0700 | [diff] [blame] | 839 | loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index())) |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 840 | default: |
Joe Tsai | ca46d8c | 2019-03-20 16:51:09 -0700 | [diff] [blame] | 841 | loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index())) |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 842 | } |
Joe Tsai | 2e7817f | 2019-08-23 12:18:57 -0700 | [diff] [blame] | 843 | camelCased := strs.GoCamelCase(string(desc.Name())) |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 844 | var parentPrefix string |
| 845 | if message != nil { |
| 846 | parentPrefix = message.GoIdent.GoName + "_" |
| 847 | } |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 848 | field := &Field{ |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 849 | Desc: desc, |
| 850 | GoName: camelCased, |
| 851 | GoIdent: GoIdent{ |
| 852 | GoImportPath: f.GoImportPath, |
| 853 | GoName: parentPrefix + camelCased, |
| 854 | }, |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 855 | Parent: message, |
| 856 | Location: loc, |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 857 | Comments: f.comments[newPathKey(loc.Path)], |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 858 | } |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 859 | return field |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 860 | } |
| 861 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 862 | func (field *Field) resolveDependencies(gen *Plugin) error { |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 863 | desc := field.Desc |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 864 | switch desc.Kind() { |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 865 | case protoreflect.EnumKind: |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 866 | name := field.Desc.Enum().FullName() |
| 867 | enum, ok := gen.enumsByName[name] |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 868 | if !ok { |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 869 | return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name) |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 870 | } |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 871 | field.Enum = enum |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 872 | case protoreflect.MessageKind, protoreflect.GroupKind: |
| 873 | name := desc.Message().FullName() |
| 874 | message, ok := gen.messagesByName[name] |
| 875 | if !ok { |
| 876 | return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name) |
| 877 | } |
| 878 | field.Message = message |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 879 | } |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 880 | if desc.IsExtension() { |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 881 | name := desc.ContainingMessage().FullName() |
| 882 | message, ok := gen.messagesByName[name] |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 883 | if !ok { |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 884 | return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name) |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 885 | } |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 886 | field.Extendee = message |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 887 | } |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 888 | return nil |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 889 | } |
| 890 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 891 | // A Oneof describes a message oneof. |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 892 | type Oneof struct { |
| 893 | Desc protoreflect.OneofDescriptor |
| 894 | |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 895 | // GoName is the base name of this oneof's Go field and methods. |
| 896 | // For code generated by protoc-gen-go, this means a field named |
| 897 | // '{{GoName}}' and a getter method named 'Get{{GoName}}'. |
| 898 | GoName string // e.g., "OneofName" |
| 899 | |
| 900 | // GoIdent is the base name of a top-level declaration for this oneof. |
| 901 | GoIdent GoIdent // e.g., "MessageName_OneofName" |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 902 | |
| 903 | Parent *Message // message in which this oneof is declared |
| 904 | |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 905 | Fields []*Field // fields that are part of this oneof |
| 906 | |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 907 | Location Location // location of this oneof |
| 908 | Comments CommentSet // comments associated with this oneof |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 909 | } |
| 910 | |
| 911 | func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof { |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 912 | loc := message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index())) |
Joe Tsai | 2e7817f | 2019-08-23 12:18:57 -0700 | [diff] [blame] | 913 | camelCased := strs.GoCamelCase(string(desc.Name())) |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 914 | parentPrefix := message.GoIdent.GoName + "_" |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 915 | return &Oneof{ |
Joe Tsai | ef6e524 | 2019-08-21 00:55:36 -0700 | [diff] [blame] | 916 | Desc: desc, |
| 917 | Parent: message, |
| 918 | GoName: camelCased, |
| 919 | GoIdent: GoIdent{ |
| 920 | GoImportPath: f.GoImportPath, |
| 921 | GoName: parentPrefix + camelCased, |
| 922 | }, |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 923 | Location: loc, |
| 924 | Comments: f.comments[newPathKey(loc.Path)], |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 925 | } |
| 926 | } |
| 927 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 928 | // Extension is an alias of Field for documentation. |
| 929 | type Extension = Field |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 930 | |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 931 | // A Service describes a service. |
| 932 | type Service struct { |
| 933 | Desc protoreflect.ServiceDescriptor |
| 934 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 935 | GoName string |
| 936 | |
| 937 | Methods []*Method // service method declarations |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 938 | |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 939 | Location Location // location of this service |
| 940 | Comments CommentSet // comments associated with this service |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 941 | } |
| 942 | |
| 943 | func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service { |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 944 | loc := f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index())) |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 945 | service := &Service{ |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 946 | Desc: desc, |
Joe Tsai | 2e7817f | 2019-08-23 12:18:57 -0700 | [diff] [blame] | 947 | GoName: strs.GoCamelCase(string(desc.Name())), |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 948 | Location: loc, |
| 949 | Comments: f.comments[newPathKey(loc.Path)], |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 950 | } |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 951 | for i, mds := 0, desc.Methods(); i < mds.Len(); i++ { |
| 952 | service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i))) |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 953 | } |
| 954 | return service |
| 955 | } |
| 956 | |
| 957 | // A Method describes a method in a service. |
| 958 | type Method struct { |
| 959 | Desc protoreflect.MethodDescriptor |
| 960 | |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 961 | GoName string |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 962 | |
| 963 | Parent *Service // service in which this method is declared |
| 964 | |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 965 | Input *Message |
| 966 | Output *Message |
| 967 | |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 968 | Location Location // location of this method |
| 969 | Comments CommentSet // comments associated with this method |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 970 | } |
| 971 | |
| 972 | func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method { |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 973 | loc := service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index())) |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 974 | method := &Method{ |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 975 | Desc: desc, |
Joe Tsai | 2e7817f | 2019-08-23 12:18:57 -0700 | [diff] [blame] | 976 | GoName: strs.GoCamelCase(string(desc.Name())), |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 977 | Parent: service, |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 978 | Location: loc, |
| 979 | Comments: f.comments[newPathKey(loc.Path)], |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 980 | } |
| 981 | return method |
| 982 | } |
| 983 | |
Joe Tsai | 7762ec2 | 2019-08-20 20:10:23 -0700 | [diff] [blame] | 984 | func (method *Method) resolveDependencies(gen *Plugin) error { |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 985 | desc := method.Desc |
| 986 | |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 987 | inName := desc.Input().FullName() |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 988 | in, ok := gen.messagesByName[inName] |
| 989 | if !ok { |
| 990 | return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName) |
| 991 | } |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 992 | method.Input = in |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 993 | |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 994 | outName := desc.Output().FullName() |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 995 | out, ok := gen.messagesByName[outName] |
| 996 | if !ok { |
| 997 | return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName) |
| 998 | } |
Joe Tsai | d24bc72 | 2019-04-15 23:39:09 -0700 | [diff] [blame] | 999 | method.Output = out |
Damien Neil | 2dc6718 | 2018-09-21 15:03:34 -0700 | [diff] [blame] | 1000 | |
| 1001 | return nil |
| 1002 | } |
| 1003 | |
Damien Neil | 7bf3ce2 | 2018-12-21 15:54:06 -0800 | [diff] [blame] | 1004 | // A GeneratedFile is a generated file. |
| 1005 | type GeneratedFile struct { |
| 1006 | gen *Plugin |
| 1007 | skip bool |
| 1008 | filename string |
| 1009 | goImportPath GoImportPath |
| 1010 | buf bytes.Buffer |
| 1011 | packageNames map[GoImportPath]GoPackageName |
| 1012 | usedPackageNames map[GoPackageName]bool |
| 1013 | manualImports map[GoImportPath]bool |
| 1014 | annotations map[string][]Location |
| 1015 | } |
| 1016 | |
| 1017 | // NewGeneratedFile creates a new generated file with the given filename |
| 1018 | // and import path. |
| 1019 | func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile { |
| 1020 | g := &GeneratedFile{ |
| 1021 | gen: gen, |
| 1022 | filename: filename, |
| 1023 | goImportPath: goImportPath, |
| 1024 | packageNames: make(map[GoImportPath]GoPackageName), |
| 1025 | usedPackageNames: make(map[GoPackageName]bool), |
| 1026 | manualImports: make(map[GoImportPath]bool), |
| 1027 | annotations: make(map[string][]Location), |
| 1028 | } |
Joe Tsai | 124c812 | 2019-01-14 11:48:43 -0800 | [diff] [blame] | 1029 | |
| 1030 | // All predeclared identifiers in Go are already used. |
| 1031 | for _, s := range types.Universe.Names() { |
| 1032 | g.usedPackageNames[GoPackageName(s)] = true |
| 1033 | } |
| 1034 | |
Damien Neil | 7bf3ce2 | 2018-12-21 15:54:06 -0800 | [diff] [blame] | 1035 | gen.genFiles = append(gen.genFiles, g) |
| 1036 | return g |
| 1037 | } |
| 1038 | |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 1039 | // P prints a line to the generated output. It converts each parameter to a |
| 1040 | // string following the same rules as fmt.Print. It never inserts spaces |
| 1041 | // between parameters. |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 1042 | func (g *GeneratedFile) P(v ...interface{}) { |
| 1043 | for _, x := range v { |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 1044 | switch x := x.(type) { |
| 1045 | case GoIdent: |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 1046 | fmt.Fprint(&g.buf, g.QualifiedGoIdent(x)) |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 1047 | default: |
| 1048 | fmt.Fprint(&g.buf, x) |
| 1049 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 1050 | } |
| 1051 | fmt.Fprintln(&g.buf) |
| 1052 | } |
| 1053 | |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 1054 | // QualifiedGoIdent returns the string to use for a Go identifier. |
| 1055 | // |
| 1056 | // If the identifier is from a different Go package than the generated file, |
| 1057 | // the returned name will be qualified (package.name) and an import statement |
| 1058 | // for the identifier's package will be included in the file. |
| 1059 | func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string { |
| 1060 | if ident.GoImportPath == g.goImportPath { |
| 1061 | return ident.GoName |
| 1062 | } |
| 1063 | if packageName, ok := g.packageNames[ident.GoImportPath]; ok { |
| 1064 | return string(packageName) + "." + ident.GoName |
| 1065 | } |
| 1066 | packageName := cleanPackageName(baseName(string(ident.GoImportPath))) |
Joe Tsai | 124c812 | 2019-01-14 11:48:43 -0800 | [diff] [blame] | 1067 | for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ { |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 1068 | packageName = orig + GoPackageName(strconv.Itoa(i)) |
| 1069 | } |
| 1070 | g.packageNames[ident.GoImportPath] = packageName |
| 1071 | g.usedPackageNames[packageName] = true |
| 1072 | return string(packageName) + "." + ident.GoName |
| 1073 | } |
| 1074 | |
Damien Neil | 2e0c3da | 2018-09-19 12:51:36 -0700 | [diff] [blame] | 1075 | // Import ensures a package is imported by the generated file. |
| 1076 | // |
| 1077 | // Packages referenced by QualifiedGoIdent are automatically imported. |
| 1078 | // Explicitly importing a package with Import is generally only necessary |
| 1079 | // when the import will be blank (import _ "package"). |
| 1080 | func (g *GeneratedFile) Import(importPath GoImportPath) { |
| 1081 | g.manualImports[importPath] = true |
| 1082 | } |
| 1083 | |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 1084 | // Write implements io.Writer. |
| 1085 | func (g *GeneratedFile) Write(p []byte) (n int, err error) { |
| 1086 | return g.buf.Write(p) |
| 1087 | } |
| 1088 | |
Damien Neil | 7bf3ce2 | 2018-12-21 15:54:06 -0800 | [diff] [blame] | 1089 | // Skip removes the generated file from the plugin output. |
| 1090 | func (g *GeneratedFile) Skip() { |
| 1091 | g.skip = true |
| 1092 | } |
| 1093 | |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1094 | // Annotate associates a symbol in a generated Go file with a location in a |
| 1095 | // source .proto file. |
| 1096 | // |
| 1097 | // The symbol may refer to a type, constant, variable, function, method, or |
| 1098 | // struct field. The "T.sel" syntax is used to identify the method or field |
| 1099 | // 'sel' on type 'T'. |
| 1100 | func (g *GeneratedFile) Annotate(symbol string, loc Location) { |
| 1101 | g.annotations[symbol] = append(g.annotations[symbol], loc) |
| 1102 | } |
| 1103 | |
Damien Neil | 7bf3ce2 | 2018-12-21 15:54:06 -0800 | [diff] [blame] | 1104 | // Content returns the contents of the generated file. |
| 1105 | func (g *GeneratedFile) Content() ([]byte, error) { |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 1106 | if !strings.HasSuffix(g.filename, ".go") { |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 1107 | return g.buf.Bytes(), nil |
| 1108 | } |
| 1109 | |
| 1110 | // Reformat generated code. |
| 1111 | original := g.buf.Bytes() |
| 1112 | fset := token.NewFileSet() |
Damien Neil | 1ec3315 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 1113 | file, err := parser.ParseFile(fset, "", original, parser.ParseComments) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 1114 | if err != nil { |
| 1115 | // Print out the bad code with line numbers. |
| 1116 | // This should never happen in practice, but it can while changing generated code |
| 1117 | // so consider this a debugging aid. |
| 1118 | var src bytes.Buffer |
| 1119 | s := bufio.NewScanner(bytes.NewReader(original)) |
| 1120 | for line := 1; s.Scan(); line++ { |
| 1121 | fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes()) |
| 1122 | } |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 1123 | return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String()) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 1124 | } |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 1125 | |
Joe Tsai | beda404 | 2019-03-10 16:40:48 -0700 | [diff] [blame] | 1126 | // Collect a sorted list of all imports. |
| 1127 | var importPaths [][2]string |
Damien Neil | 1fa8ab0 | 2018-09-27 15:51:05 -0700 | [diff] [blame] | 1128 | rewriteImport := func(importPath string) string { |
| 1129 | if f := g.gen.opts.ImportRewriteFunc; f != nil { |
| 1130 | return string(f(GoImportPath(importPath))) |
| 1131 | } |
| 1132 | return importPath |
| 1133 | } |
Joe Tsai | beda404 | 2019-03-10 16:40:48 -0700 | [diff] [blame] | 1134 | for importPath := range g.packageNames { |
| 1135 | pkgName := string(g.packageNames[GoImportPath(importPath)]) |
| 1136 | pkgPath := rewriteImport(string(importPath)) |
| 1137 | importPaths = append(importPaths, [2]string{pkgName, pkgPath}) |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 1138 | } |
Damien Neil | 2e0c3da | 2018-09-19 12:51:36 -0700 | [diff] [blame] | 1139 | for importPath := range g.manualImports { |
Joe Tsai | beda404 | 2019-03-10 16:40:48 -0700 | [diff] [blame] | 1140 | if _, ok := g.packageNames[importPath]; !ok { |
| 1141 | pkgPath := rewriteImport(string(importPath)) |
| 1142 | importPaths = append(importPaths, [2]string{"_", pkgPath}) |
Damien Neil | 2e0c3da | 2018-09-19 12:51:36 -0700 | [diff] [blame] | 1143 | } |
Damien Neil | 2e0c3da | 2018-09-19 12:51:36 -0700 | [diff] [blame] | 1144 | } |
Joe Tsai | beda404 | 2019-03-10 16:40:48 -0700 | [diff] [blame] | 1145 | sort.Slice(importPaths, func(i, j int) bool { |
| 1146 | return importPaths[i][1] < importPaths[j][1] |
| 1147 | }) |
| 1148 | |
| 1149 | // Modify the AST to include a new import block. |
| 1150 | if len(importPaths) > 0 { |
| 1151 | // Insert block after package statement or |
| 1152 | // possible comment attached to the end of the package statement. |
| 1153 | pos := file.Package |
| 1154 | tokFile := fset.File(file.Package) |
| 1155 | pkgLine := tokFile.Line(file.Package) |
| 1156 | for _, c := range file.Comments { |
| 1157 | if tokFile.Line(c.Pos()) > pkgLine { |
| 1158 | break |
| 1159 | } |
| 1160 | pos = c.End() |
| 1161 | } |
| 1162 | |
| 1163 | // Construct the import block. |
| 1164 | impDecl := &ast.GenDecl{ |
| 1165 | Tok: token.IMPORT, |
| 1166 | TokPos: pos, |
| 1167 | Lparen: pos, |
| 1168 | Rparen: pos, |
| 1169 | } |
| 1170 | for _, importPath := range importPaths { |
| 1171 | impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{ |
| 1172 | Name: &ast.Ident{ |
| 1173 | Name: importPath[0], |
| 1174 | NamePos: pos, |
| 1175 | }, |
| 1176 | Path: &ast.BasicLit{ |
| 1177 | Kind: token.STRING, |
| 1178 | Value: strconv.Quote(importPath[1]), |
| 1179 | ValuePos: pos, |
| 1180 | }, |
| 1181 | EndPos: pos, |
| 1182 | }) |
| 1183 | } |
| 1184 | file.Decls = append([]ast.Decl{impDecl}, file.Decls...) |
| 1185 | } |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 1186 | |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 1187 | var out bytes.Buffer |
Damien Neil | 1ec3315 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 1188 | if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil { |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 1189 | return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 1190 | } |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 1191 | return out.Bytes(), nil |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1192 | } |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 1193 | |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1194 | // metaFile returns the contents of the file's metadata file, which is a |
| 1195 | // text formatted string of the google.protobuf.GeneratedCodeInfo. |
| 1196 | func (g *GeneratedFile) metaFile(content []byte) (string, error) { |
| 1197 | fset := token.NewFileSet() |
| 1198 | astFile, err := parser.ParseFile(fset, "", content, 0) |
| 1199 | if err != nil { |
| 1200 | return "", err |
| 1201 | } |
Joe Tsai | e1f8d50 | 2018-11-26 18:55:29 -0800 | [diff] [blame] | 1202 | info := &descriptorpb.GeneratedCodeInfo{} |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1203 | |
| 1204 | seenAnnotations := make(map[string]bool) |
| 1205 | annotate := func(s string, ident *ast.Ident) { |
| 1206 | seenAnnotations[s] = true |
| 1207 | for _, loc := range g.annotations[s] { |
Joe Tsai | e1f8d50 | 2018-11-26 18:55:29 -0800 | [diff] [blame] | 1208 | info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{ |
Damien Neil | a8a2cea | 2019-07-10 16:17:16 -0700 | [diff] [blame] | 1209 | SourceFile: proto.String(loc.SourceFile), |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1210 | Path: loc.Path, |
Damien Neil | a8a2cea | 2019-07-10 16:17:16 -0700 | [diff] [blame] | 1211 | Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)), |
| 1212 | End: proto.Int32(int32(fset.Position(ident.End()).Offset)), |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1213 | }) |
| 1214 | } |
| 1215 | } |
| 1216 | for _, decl := range astFile.Decls { |
| 1217 | switch decl := decl.(type) { |
| 1218 | case *ast.GenDecl: |
| 1219 | for _, spec := range decl.Specs { |
| 1220 | switch spec := spec.(type) { |
| 1221 | case *ast.TypeSpec: |
| 1222 | annotate(spec.Name.Name, spec.Name) |
Damien Neil | ae2a561 | 2018-12-12 08:54:57 -0800 | [diff] [blame] | 1223 | switch st := spec.Type.(type) { |
| 1224 | case *ast.StructType: |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1225 | for _, field := range st.Fields.List { |
| 1226 | for _, name := range field.Names { |
| 1227 | annotate(spec.Name.Name+"."+name.Name, name) |
| 1228 | } |
| 1229 | } |
Damien Neil | ae2a561 | 2018-12-12 08:54:57 -0800 | [diff] [blame] | 1230 | case *ast.InterfaceType: |
| 1231 | for _, field := range st.Methods.List { |
| 1232 | for _, name := range field.Names { |
| 1233 | annotate(spec.Name.Name+"."+name.Name, name) |
| 1234 | } |
| 1235 | } |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1236 | } |
| 1237 | case *ast.ValueSpec: |
| 1238 | for _, name := range spec.Names { |
| 1239 | annotate(name.Name, name) |
| 1240 | } |
| 1241 | } |
| 1242 | } |
| 1243 | case *ast.FuncDecl: |
| 1244 | if decl.Recv == nil { |
| 1245 | annotate(decl.Name.Name, decl.Name) |
| 1246 | } else { |
| 1247 | recv := decl.Recv.List[0].Type |
| 1248 | if s, ok := recv.(*ast.StarExpr); ok { |
| 1249 | recv = s.X |
| 1250 | } |
| 1251 | if id, ok := recv.(*ast.Ident); ok { |
| 1252 | annotate(id.Name+"."+decl.Name.Name, decl.Name) |
| 1253 | } |
| 1254 | } |
| 1255 | } |
| 1256 | } |
| 1257 | for a := range g.annotations { |
| 1258 | if !seenAnnotations[a] { |
| 1259 | return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a) |
| 1260 | } |
| 1261 | } |
| 1262 | |
Damien Neil | 5c5b531 | 2019-05-14 12:44:37 -0700 | [diff] [blame] | 1263 | b, err := prototext.Marshal(info) |
Joe Tsai | f31bf26 | 2019-03-18 14:54:34 -0700 | [diff] [blame] | 1264 | if err != nil { |
| 1265 | return "", err |
| 1266 | } |
| 1267 | return string(b), nil |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 1268 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 1269 | |
Joe Tsai | 2e7817f | 2019-08-23 12:18:57 -0700 | [diff] [blame] | 1270 | // A GoIdent is a Go identifier, consisting of a name and import path. |
| 1271 | // The name is a single identifier and may not be a dot-qualified selector. |
| 1272 | type GoIdent struct { |
| 1273 | GoName string |
| 1274 | GoImportPath GoImportPath |
| 1275 | } |
| 1276 | |
| 1277 | func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) } |
| 1278 | |
| 1279 | // newGoIdent returns the Go identifier for a descriptor. |
| 1280 | func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent { |
| 1281 | name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".") |
| 1282 | return GoIdent{ |
| 1283 | GoName: strs.GoCamelCase(name), |
| 1284 | GoImportPath: f.GoImportPath, |
| 1285 | } |
| 1286 | } |
| 1287 | |
| 1288 | // A GoImportPath is the import path of a Go package. |
| 1289 | // For example: "google.golang.org/protobuf/compiler/protogen" |
| 1290 | type GoImportPath string |
| 1291 | |
| 1292 | func (p GoImportPath) String() string { return strconv.Quote(string(p)) } |
| 1293 | |
| 1294 | // Ident returns a GoIdent with s as the GoName and p as the GoImportPath. |
| 1295 | func (p GoImportPath) Ident(s string) GoIdent { |
| 1296 | return GoIdent{GoName: s, GoImportPath: p} |
| 1297 | } |
| 1298 | |
| 1299 | // A GoPackageName is the name of a Go package. e.g., "protobuf". |
| 1300 | type GoPackageName string |
| 1301 | |
| 1302 | // cleanPackageName converts a string to a valid Go package name. |
| 1303 | func cleanPackageName(name string) GoPackageName { |
| 1304 | return GoPackageName(strs.GoSanitized(name)) |
| 1305 | } |
| 1306 | |
| 1307 | // baseName returns the last path element of the name, with the last dotted suffix removed. |
| 1308 | func baseName(name string) string { |
| 1309 | // First, find the last element |
| 1310 | if i := strings.LastIndex(name, "/"); i >= 0 { |
| 1311 | name = name[i+1:] |
| 1312 | } |
| 1313 | // Now drop the suffix |
| 1314 | if i := strings.LastIndex(name, "."); i >= 0 { |
| 1315 | name = name[:i] |
| 1316 | } |
| 1317 | return name |
| 1318 | } |
| 1319 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 1320 | type pathType int |
| 1321 | |
| 1322 | const ( |
Damien Neil | aadba56 | 2020-02-15 14:28:51 -0800 | [diff] [blame] | 1323 | pathTypeLegacy pathType = iota |
| 1324 | pathTypeImport |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 1325 | pathTypeSourceRelative |
| 1326 | ) |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 1327 | |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1328 | // A Location is a location in a .proto source file. |
| 1329 | // |
| 1330 | // See the google.protobuf.SourceCodeInfo documentation in descriptor.proto |
| 1331 | // for details. |
| 1332 | type Location struct { |
| 1333 | SourceFile string |
Joe Tsai | 691d856 | 2019-07-12 17:16:36 -0700 | [diff] [blame] | 1334 | Path protoreflect.SourcePath |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1335 | } |
| 1336 | |
| 1337 | // appendPath add elements to a Location's path, returning a new Location. |
| 1338 | func (loc Location) appendPath(a ...int32) Location { |
Joe Tsai | 691d856 | 2019-07-12 17:16:36 -0700 | [diff] [blame] | 1339 | var n protoreflect.SourcePath |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1340 | n = append(n, loc.Path...) |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 1341 | n = append(n, a...) |
Damien Neil | 162c127 | 2018-10-04 12:42:37 -0700 | [diff] [blame] | 1342 | return Location{ |
| 1343 | SourceFile: loc.SourceFile, |
| 1344 | Path: n, |
| 1345 | } |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 1346 | } |
Damien Neil | ba1159f | 2018-10-17 12:53:18 -0700 | [diff] [blame] | 1347 | |
| 1348 | // A pathKey is a representation of a location path suitable for use as a map key. |
| 1349 | type pathKey struct { |
| 1350 | s string |
| 1351 | } |
| 1352 | |
| 1353 | // newPathKey converts a location path to a pathKey. |
Koichi Shiraishi | ea2076d | 2019-05-24 18:24:29 +0900 | [diff] [blame] | 1354 | func newPathKey(idxPath []int32) pathKey { |
| 1355 | buf := make([]byte, 4*len(idxPath)) |
| 1356 | for i, x := range idxPath { |
Damien Neil | ba1159f | 2018-10-17 12:53:18 -0700 | [diff] [blame] | 1357 | binary.LittleEndian.PutUint32(buf[i*4:], uint32(x)) |
| 1358 | } |
| 1359 | return pathKey{string(buf)} |
| 1360 | } |
Joe Tsai | 70fdd5d | 2019-08-06 01:15:18 -0700 | [diff] [blame] | 1361 | |
| 1362 | // CommentSet is a set of leading and trailing comments associated |
| 1363 | // with a .proto descriptor declaration. |
| 1364 | type CommentSet struct { |
| 1365 | LeadingDetached []Comments |
| 1366 | Leading Comments |
| 1367 | Trailing Comments |
| 1368 | } |
| 1369 | |
| 1370 | // Comments is a comments string as provided by protoc. |
| 1371 | type Comments string |
| 1372 | |
| 1373 | // String formats the comments by inserting // to the start of each line, |
| 1374 | // ensuring that there is a trailing newline. |
| 1375 | // An empty comment is formatted as an empty string. |
| 1376 | func (c Comments) String() string { |
| 1377 | if c == "" { |
| 1378 | return "" |
| 1379 | } |
| 1380 | var b []byte |
| 1381 | for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") { |
| 1382 | b = append(b, "//"...) |
| 1383 | b = append(b, line...) |
| 1384 | b = append(b, "\n"...) |
| 1385 | } |
| 1386 | return string(b) |
| 1387 | } |
Damien Neil | e358d43 | 2020-03-06 13:58:41 -0800 | [diff] [blame] | 1388 | |
| 1389 | var warnings = true |
| 1390 | |
| 1391 | func warn(format string, a ...interface{}) { |
| 1392 | if warnings { |
| 1393 | log.Printf("WARNING: "+format, a...) |
| 1394 | } |
| 1395 | } |