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