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" |
| 16 | "fmt" |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 17 | "go/parser" |
| 18 | "go/printer" |
| 19 | "go/token" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 20 | "io/ioutil" |
| 21 | "os" |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 22 | "path" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 23 | "path/filepath" |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 24 | "sort" |
| 25 | "strconv" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 26 | "strings" |
| 27 | |
| 28 | "github.com/golang/protobuf/proto" |
| 29 | descpb "github.com/golang/protobuf/protoc-gen-go/descriptor" |
| 30 | pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin" |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 31 | "golang.org/x/tools/go/ast/astutil" |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 32 | "google.golang.org/proto/reflect/protoreflect" |
| 33 | "google.golang.org/proto/reflect/protoregistry" |
| 34 | "google.golang.org/proto/reflect/prototype" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 35 | ) |
| 36 | |
| 37 | // Run executes a function as a protoc plugin. |
| 38 | // |
| 39 | // It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin |
| 40 | // function, and writes a CodeGeneratorResponse message to os.Stdout. |
| 41 | // |
| 42 | // If a failure occurs while reading or writing, Run prints an error to |
| 43 | // os.Stderr and calls os.Exit(1). |
| 44 | func Run(f func(*Plugin) error) { |
| 45 | if err := run(f); err != nil { |
| 46 | fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err) |
| 47 | os.Exit(1) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | func run(f func(*Plugin) error) error { |
| 52 | in, err := ioutil.ReadAll(os.Stdin) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | req := &pluginpb.CodeGeneratorRequest{} |
| 57 | if err := proto.Unmarshal(in, req); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | gen, err := New(req) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | if err := f(gen); err != nil { |
| 65 | // Errors from the plugin function are reported by setting the |
| 66 | // error field in the CodeGeneratorResponse. |
| 67 | // |
| 68 | // In contrast, errors that indicate a problem in protoc |
| 69 | // itself (unparsable input, I/O errors, etc.) are reported |
| 70 | // to stderr. |
| 71 | gen.Error(err) |
| 72 | } |
| 73 | resp := gen.Response() |
| 74 | out, err := proto.Marshal(resp) |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | if _, err := os.Stdout.Write(out); err != nil { |
| 79 | return err |
| 80 | } |
| 81 | return nil |
| 82 | } |
| 83 | |
| 84 | // A Plugin is a protoc plugin invocation. |
| 85 | type Plugin struct { |
| 86 | // Request is the CodeGeneratorRequest provided by protoc. |
| 87 | Request *pluginpb.CodeGeneratorRequest |
| 88 | |
| 89 | // Files is the set of files to generate and everything they import. |
| 90 | // Files appear in topological order, so each file appears before any |
| 91 | // file that imports it. |
| 92 | Files []*File |
| 93 | filesByName map[string]*File |
| 94 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 95 | fileReg *protoregistry.Files |
| 96 | pathType pathType |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 97 | genFiles []*GeneratedFile |
| 98 | err error |
| 99 | } |
| 100 | |
| 101 | // New returns a new Plugin. |
| 102 | func New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) { |
| 103 | gen := &Plugin{ |
| 104 | Request: req, |
| 105 | filesByName: make(map[string]*File), |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 106 | fileReg: protoregistry.NewFiles(), |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 107 | } |
| 108 | |
| 109 | // TODO: Figure out how to pass parameters to the generator. |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 110 | packageNames := make(map[string]GoPackageName) // filename -> package name |
| 111 | importPaths := make(map[string]GoImportPath) // filename -> import path |
| 112 | var packageImportPath GoImportPath |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 113 | for _, param := range strings.Split(req.GetParameter(), ",") { |
| 114 | var value string |
| 115 | if i := strings.Index(param, "="); i >= 0 { |
| 116 | value = param[i+1:] |
| 117 | param = param[0:i] |
| 118 | } |
| 119 | switch param { |
| 120 | case "": |
| 121 | // Ignore. |
| 122 | case "import_prefix": |
| 123 | // TODO |
| 124 | case "import_path": |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 125 | packageImportPath = GoImportPath(value) |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 126 | case "paths": |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 127 | switch value { |
| 128 | case "import": |
| 129 | gen.pathType = pathTypeImport |
| 130 | case "source_relative": |
| 131 | gen.pathType = pathTypeSourceRelative |
| 132 | default: |
| 133 | return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value) |
| 134 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 135 | case "plugins": |
| 136 | // TODO |
| 137 | case "annotate_code": |
| 138 | // TODO |
| 139 | default: |
| 140 | if param[0] != 'M' { |
| 141 | return nil, fmt.Errorf("unknown parameter %q", param) |
| 142 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 143 | importPaths[param[1:]] = GoImportPath(value) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | // Figure out the import path and package name for each file. |
| 148 | // |
| 149 | // The rules here are complicated and have grown organically over time. |
| 150 | // Interactions between different ways of specifying package information |
| 151 | // may be surprising. |
| 152 | // |
| 153 | // The recommended approach is to include a go_package option in every |
| 154 | // .proto source file specifying the full import path of the Go package |
| 155 | // associated with this file. |
| 156 | // |
| 157 | // option go_package = "github.com/golang/protobuf/ptypes/any"; |
| 158 | // |
| 159 | // Build systems which want to exert full control over import paths may |
| 160 | // specify M<filename>=<import_path> flags. |
| 161 | // |
| 162 | // Other approaches are not recommend. |
| 163 | generatedFileNames := make(map[string]bool) |
| 164 | for _, name := range gen.Request.FileToGenerate { |
| 165 | generatedFileNames[name] = true |
| 166 | } |
| 167 | // We need to determine the import paths before the package names, |
| 168 | // because the Go package name for a file is sometimes derived from |
| 169 | // different file in the same package. |
| 170 | packageNameForImportPath := make(map[GoImportPath]GoPackageName) |
| 171 | for _, fdesc := range gen.Request.ProtoFile { |
| 172 | filename := fdesc.GetName() |
| 173 | packageName, importPath := goPackageOption(fdesc) |
| 174 | switch { |
| 175 | case importPaths[filename] != "": |
| 176 | // Command line: M=foo.proto=quux/bar |
| 177 | // |
| 178 | // Explicit mapping of source file to import path. |
| 179 | case generatedFileNames[filename] && packageImportPath != "": |
| 180 | // Command line: import_path=quux/bar |
| 181 | // |
| 182 | // The import_path flag sets the import path for every file that |
| 183 | // we generate code for. |
| 184 | importPaths[filename] = packageImportPath |
| 185 | case importPath != "": |
| 186 | // Source file: option go_package = "quux/bar"; |
| 187 | // |
| 188 | // The go_package option sets the import path. Most users should use this. |
| 189 | importPaths[filename] = importPath |
| 190 | default: |
| 191 | // Source filename. |
| 192 | // |
| 193 | // Last resort when nothing else is available. |
| 194 | importPaths[filename] = GoImportPath(path.Dir(filename)) |
| 195 | } |
| 196 | if packageName != "" { |
| 197 | packageNameForImportPath[importPaths[filename]] = packageName |
| 198 | } |
| 199 | } |
| 200 | for _, fdesc := range gen.Request.ProtoFile { |
| 201 | filename := fdesc.GetName() |
| 202 | packageName, _ := goPackageOption(fdesc) |
| 203 | defaultPackageName := packageNameForImportPath[importPaths[filename]] |
| 204 | switch { |
| 205 | case packageName != "": |
| 206 | // Source file: option go_package = "quux/bar"; |
| 207 | packageNames[filename] = packageName |
| 208 | case defaultPackageName != "": |
| 209 | // A go_package option in another file in the same package. |
| 210 | // |
| 211 | // This is a poor choice in general, since every source file should |
| 212 | // contain a go_package option. Supported mainly for historical |
| 213 | // compatibility. |
| 214 | packageNames[filename] = defaultPackageName |
| 215 | case generatedFileNames[filename] && packageImportPath != "": |
| 216 | // Command line: import_path=quux/bar |
| 217 | packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath))) |
| 218 | case fdesc.GetPackage() != "": |
| 219 | // Source file: package quux.bar; |
| 220 | packageNames[filename] = cleanPackageName(fdesc.GetPackage()) |
| 221 | default: |
| 222 | // Source filename. |
| 223 | packageNames[filename] = cleanPackageName(baseName(filename)) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | // Consistency check: Every file with the same Go import path should have |
| 228 | // the same Go package name. |
| 229 | packageFiles := make(map[GoImportPath][]string) |
| 230 | for filename, importPath := range importPaths { |
| 231 | packageFiles[importPath] = append(packageFiles[importPath], filename) |
| 232 | } |
| 233 | for importPath, filenames := range packageFiles { |
| 234 | for i := 1; i < len(filenames); i++ { |
| 235 | if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b { |
| 236 | return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)", |
| 237 | importPath, a, filenames[0], b, filenames[i]) |
| 238 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 239 | } |
| 240 | } |
| 241 | |
| 242 | for _, fdesc := range gen.Request.ProtoFile { |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 243 | filename := fdesc.GetName() |
| 244 | if gen.filesByName[filename] != nil { |
| 245 | return nil, fmt.Errorf("duplicate file name: %q", filename) |
| 246 | } |
| 247 | f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename]) |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 248 | if err != nil { |
| 249 | return nil, err |
| 250 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 251 | gen.Files = append(gen.Files, f) |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 252 | gen.filesByName[filename] = f |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 253 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 254 | for _, filename := range gen.Request.FileToGenerate { |
| 255 | f, ok := gen.FileByName(filename) |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 256 | if !ok { |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 257 | return nil, fmt.Errorf("no descriptor for generated file: %v", filename) |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 258 | } |
| 259 | f.Generate = true |
| 260 | } |
| 261 | return gen, nil |
| 262 | } |
| 263 | |
| 264 | // Error records an error in code generation. The generator will report the |
| 265 | // error back to protoc and will not produce output. |
| 266 | func (gen *Plugin) Error(err error) { |
| 267 | if gen.err == nil { |
| 268 | gen.err = err |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | // Response returns the generator output. |
| 273 | func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse { |
| 274 | resp := &pluginpb.CodeGeneratorResponse{} |
| 275 | if gen.err != nil { |
| 276 | resp.Error = proto.String(gen.err.Error()) |
| 277 | return resp |
| 278 | } |
| 279 | for _, gf := range gen.genFiles { |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 280 | content, err := gf.Content() |
| 281 | if err != nil { |
| 282 | return &pluginpb.CodeGeneratorResponse{ |
| 283 | Error: proto.String(err.Error()), |
| 284 | } |
| 285 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 286 | resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{ |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 287 | Name: proto.String(gf.filename), |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 288 | Content: proto.String(string(content)), |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 289 | }) |
| 290 | } |
| 291 | return resp |
| 292 | } |
| 293 | |
| 294 | // FileByName returns the file with the given name. |
| 295 | func (gen *Plugin) FileByName(name string) (f *File, ok bool) { |
| 296 | f, ok = gen.filesByName[name] |
| 297 | return f, ok |
| 298 | } |
| 299 | |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 300 | // A File describes a .proto source file. |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 301 | type File struct { |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 302 | Desc protoreflect.FileDescriptor |
| 303 | Proto *descpb.FileDescriptorProto |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 304 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 305 | GoPackageName GoPackageName // name of this file's Go package |
| 306 | GoImportPath GoImportPath // import path of this file's Go package |
| 307 | Messages []*Message // top-level message declarations |
| 308 | Generate bool // true if we should generate code for this file |
| 309 | |
| 310 | // GeneratedFilenamePrefix is used to construct filenames for generated |
| 311 | // files associated with this source file. |
| 312 | // |
| 313 | // For example, the source file "dir/foo.proto" might have a filename prefix |
| 314 | // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go". |
| 315 | GeneratedFilenamePrefix string |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 316 | } |
| 317 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 318 | func newFile(gen *Plugin, p *descpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) { |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 319 | desc, err := prototype.NewFileFromDescriptorProto(p, gen.fileReg) |
| 320 | if err != nil { |
| 321 | return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err) |
| 322 | } |
| 323 | if err := gen.fileReg.Register(desc); err != nil { |
| 324 | return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err) |
| 325 | } |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 326 | f := &File{ |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 327 | Desc: desc, |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 328 | Proto: p, |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 329 | GoPackageName: packageName, |
| 330 | GoImportPath: importPath, |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 331 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 332 | |
| 333 | // Determine the prefix for generated Go files. |
| 334 | prefix := p.GetName() |
| 335 | if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" { |
| 336 | prefix = prefix[:len(prefix)-len(ext)] |
| 337 | } |
| 338 | if gen.pathType == pathTypeImport { |
| 339 | // If paths=import (the default) and the file contains a go_package option |
| 340 | // with a full import path, the output filename is derived from the Go import |
| 341 | // path. |
| 342 | // |
| 343 | // Pass the paths=source_relative flag to always derive the output filename |
| 344 | // from the input filename instead. |
| 345 | if _, importPath := goPackageOption(p); importPath != "" { |
| 346 | prefix = path.Join(string(importPath), path.Base(prefix)) |
| 347 | } |
| 348 | } |
| 349 | f.GeneratedFilenamePrefix = prefix |
| 350 | |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 351 | for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ { |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame^] | 352 | f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i))) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 353 | } |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 354 | return f, nil |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 355 | } |
| 356 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 357 | // goPackageOption interprets a file's go_package option. |
| 358 | // If there is no go_package, it returns ("", ""). |
| 359 | // If there's a simple name, it returns (pkg, ""). |
| 360 | // If the option implies an import path, it returns (pkg, impPath). |
| 361 | func goPackageOption(d *descpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) { |
| 362 | opt := d.GetOptions().GetGoPackage() |
| 363 | if opt == "" { |
| 364 | return "", "" |
| 365 | } |
| 366 | // A semicolon-delimited suffix delimits the import path and package name. |
| 367 | if i := strings.Index(opt, ";"); i >= 0 { |
| 368 | return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i]) |
| 369 | } |
| 370 | // The presence of a slash implies there's an import path. |
| 371 | if i := strings.LastIndex(opt, "/"); i >= 0 { |
| 372 | return cleanPackageName(opt[i+1:]), GoImportPath(opt) |
| 373 | } |
| 374 | return cleanPackageName(opt), "" |
| 375 | } |
| 376 | |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 377 | // A Message describes a message. |
| 378 | type Message struct { |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 379 | Desc protoreflect.MessageDescriptor |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 380 | |
| 381 | GoIdent GoIdent // name of the generated Go type |
| 382 | Messages []*Message // nested message declarations |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame^] | 383 | Path []int32 // location path of this message |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 384 | } |
| 385 | |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame^] | 386 | func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message { |
| 387 | var path []int32 |
| 388 | if parent != nil { |
| 389 | path = pathAppend(parent.Path, messageMessageField, int32(desc.Index())) |
| 390 | } else { |
| 391 | path = []int32{fileMessageField, int32(desc.Index())} |
| 392 | } |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 393 | m := &Message{ |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 394 | Desc: desc, |
| 395 | GoIdent: newGoIdent(f, desc), |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame^] | 396 | Path: path, |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 397 | } |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 398 | for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ { |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame^] | 399 | m.Messages = append(m.Messages, newMessage(gen, f, m, mdescs.Get(i))) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 400 | } |
| 401 | return m |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 402 | } |
| 403 | |
| 404 | // A GeneratedFile is a generated file. |
| 405 | type GeneratedFile struct { |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 406 | filename string |
| 407 | goImportPath GoImportPath |
| 408 | buf bytes.Buffer |
| 409 | packageNames map[GoImportPath]GoPackageName |
| 410 | usedPackageNames map[GoPackageName]bool |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 411 | } |
| 412 | |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 413 | // NewGeneratedFile creates a new generated file with the given filename |
| 414 | // and import path. |
| 415 | func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile { |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 416 | g := &GeneratedFile{ |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 417 | filename: filename, |
| 418 | goImportPath: goImportPath, |
| 419 | packageNames: make(map[GoImportPath]GoPackageName), |
| 420 | usedPackageNames: make(map[GoPackageName]bool), |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 421 | } |
| 422 | gen.genFiles = append(gen.genFiles, g) |
| 423 | return g |
| 424 | } |
| 425 | |
| 426 | // P prints a line to the generated output. It converts each parameter to a |
| 427 | // string following the same rules as fmt.Print. It never inserts spaces |
| 428 | // between parameters. |
| 429 | // |
| 430 | // TODO: .meta file annotations. |
| 431 | func (g *GeneratedFile) P(v ...interface{}) { |
| 432 | for _, x := range v { |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 433 | switch x := x.(type) { |
| 434 | case GoIdent: |
| 435 | if x.GoImportPath != g.goImportPath { |
| 436 | fmt.Fprint(&g.buf, g.goPackageName(x.GoImportPath)) |
| 437 | fmt.Fprint(&g.buf, ".") |
| 438 | } |
| 439 | fmt.Fprint(&g.buf, x.GoName) |
| 440 | default: |
| 441 | fmt.Fprint(&g.buf, x) |
| 442 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 443 | } |
| 444 | fmt.Fprintln(&g.buf) |
| 445 | } |
| 446 | |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 447 | func (g *GeneratedFile) goPackageName(importPath GoImportPath) GoPackageName { |
| 448 | if name, ok := g.packageNames[importPath]; ok { |
| 449 | return name |
| 450 | } |
| 451 | name := cleanPackageName(baseName(string(importPath))) |
| 452 | for i, orig := 1, name; g.usedPackageNames[name]; i++ { |
| 453 | name = orig + GoPackageName(strconv.Itoa(i)) |
| 454 | } |
| 455 | g.packageNames[importPath] = name |
| 456 | g.usedPackageNames[name] = true |
| 457 | return name |
| 458 | } |
| 459 | |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 460 | // Write implements io.Writer. |
| 461 | func (g *GeneratedFile) Write(p []byte) (n int, err error) { |
| 462 | return g.buf.Write(p) |
| 463 | } |
| 464 | |
| 465 | // Content returns the contents of the generated file. |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 466 | func (g *GeneratedFile) Content() ([]byte, error) { |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 467 | if !strings.HasSuffix(g.filename, ".go") { |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 468 | return g.buf.Bytes(), nil |
| 469 | } |
| 470 | |
| 471 | // Reformat generated code. |
| 472 | original := g.buf.Bytes() |
| 473 | fset := token.NewFileSet() |
| 474 | ast, err := parser.ParseFile(fset, "", original, parser.ParseComments) |
| 475 | if err != nil { |
| 476 | // Print out the bad code with line numbers. |
| 477 | // This should never happen in practice, but it can while changing generated code |
| 478 | // so consider this a debugging aid. |
| 479 | var src bytes.Buffer |
| 480 | s := bufio.NewScanner(bytes.NewReader(original)) |
| 481 | for line := 1; s.Scan(); line++ { |
| 482 | fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes()) |
| 483 | } |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 484 | 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] | 485 | } |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 486 | |
| 487 | // Add imports. |
| 488 | var importPaths []string |
| 489 | for importPath := range g.packageNames { |
| 490 | importPaths = append(importPaths, string(importPath)) |
| 491 | } |
| 492 | sort.Strings(importPaths) |
| 493 | for _, importPath := range importPaths { |
| 494 | astutil.AddNamedImport(fset, ast, string(g.packageNames[GoImportPath(importPath)]), importPath) |
| 495 | } |
| 496 | |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 497 | var out bytes.Buffer |
| 498 | if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, ast); err != nil { |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 499 | 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] | 500 | } |
Damien Neil | d901677 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 501 | // TODO: Annotations. |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 502 | return out.Bytes(), nil |
| 503 | |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 504 | } |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 505 | |
| 506 | type pathType int |
| 507 | |
| 508 | const ( |
| 509 | pathTypeImport pathType = iota |
| 510 | pathTypeSourceRelative |
| 511 | ) |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame^] | 512 | |
| 513 | // The SourceCodeInfo message describes the location of elements of a parsed |
| 514 | // .proto file by way of a "path", which is a sequence of integers that |
| 515 | // describe the route from a FileDescriptorProto to the relevant submessage. |
| 516 | // The path alternates between a field number of a repeated field, and an index |
| 517 | // into that repeated field. The constants below define the field numbers that |
| 518 | // are used. |
| 519 | // |
| 520 | // See descriptor.proto for more information about this. |
| 521 | const ( |
| 522 | // field numbers in FileDescriptorProto |
| 523 | filePackageField = 2 // package |
| 524 | fileMessageField = 4 // message_type |
| 525 | fileenumField = 5 // enum_type |
| 526 | // field numbers in DescriptorProto |
| 527 | messageFieldField = 2 // field |
| 528 | messageMessageField = 3 // nested_type |
| 529 | messageEnumField = 4 // enum_type |
| 530 | messageOneofField = 8 // oneof_decl |
| 531 | // field numbers in EnumDescriptorProto |
| 532 | enumValueField = 2 // value |
| 533 | ) |
| 534 | |
| 535 | // pathAppend appends elements to a location path. |
| 536 | // It does not alias the original path. |
| 537 | func pathAppend(path []int32, a ...int32) []int32 { |
| 538 | var n []int32 |
| 539 | n = append(n, path...) |
| 540 | n = append(n, a...) |
| 541 | return n |
| 542 | } |