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