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