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