blob: 8ffccca2a36bbf94fdfe414eb89dd4873212ee65 [file] [log] [blame]
Damien Neil220c2022018-08-15 11:24:18 -07001// 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.
11package protogen
12
13import (
Damien Neilc7d07d92018-08-22 13:46:02 -070014 "bufio"
Damien Neil220c2022018-08-15 11:24:18 -070015 "bytes"
Damien Neilba1159f2018-10-17 12:53:18 -070016 "encoding/binary"
Damien Neil220c2022018-08-15 11:24:18 -070017 "fmt"
Damien Neil1ec33152018-09-13 13:12:36 -070018 "go/ast"
Damien Neilc7d07d92018-08-22 13:46:02 -070019 "go/parser"
20 "go/printer"
21 "go/token"
Joe Tsai124c8122019-01-14 11:48:43 -080022 "go/types"
Damien Neil220c2022018-08-15 11:24:18 -070023 "io/ioutil"
Joe Tsai3e802492019-09-07 13:06:27 -070024 "log"
Damien Neil220c2022018-08-15 11:24:18 -070025 "os"
Damien Neil082ce922018-09-06 10:23:53 -070026 "path"
Damien Neil220c2022018-08-15 11:24:18 -070027 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070028 "sort"
29 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070030 "strings"
31
Damien Neil5c5b5312019-05-14 12:44:37 -070032 "google.golang.org/protobuf/encoding/prototext"
Damien Neile89e6242019-05-13 23:55:40 -070033 "google.golang.org/protobuf/internal/fieldnum"
Joe Tsai2e7817f2019-08-23 12:18:57 -070034 "google.golang.org/protobuf/internal/strs"
Damien Neile89e6242019-05-13 23:55:40 -070035 "google.golang.org/protobuf/proto"
36 "google.golang.org/protobuf/reflect/protodesc"
37 "google.golang.org/protobuf/reflect/protoreflect"
38 "google.golang.org/protobuf/reflect/protoregistry"
Joe Tsaie1f8d502018-11-26 18:55:29 -080039
Joe Tsaia95b29f2019-05-16 12:47:20 -070040 "google.golang.org/protobuf/types/descriptorpb"
41 "google.golang.org/protobuf/types/pluginpb"
Damien Neil220c2022018-08-15 11:24:18 -070042)
43
44// Run executes a function as a protoc plugin.
45//
46// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
47// function, and writes a CodeGeneratorResponse message to os.Stdout.
48//
49// If a failure occurs while reading or writing, Run prints an error to
50// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070051//
52// Passing a nil options is equivalent to passing a zero-valued one.
53func Run(opts *Options, f func(*Plugin) error) {
54 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070055 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
56 os.Exit(1)
57 }
58}
59
Damien Neil3cf6e622018-09-11 13:53:14 -070060func run(opts *Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070061 if len(os.Args) > 1 {
62 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
63 }
Damien Neil220c2022018-08-15 11:24:18 -070064 in, err := ioutil.ReadAll(os.Stdin)
65 if err != nil {
66 return err
67 }
68 req := &pluginpb.CodeGeneratorRequest{}
69 if err := proto.Unmarshal(in, req); err != nil {
70 return err
71 }
Damien Neil3cf6e622018-09-11 13:53:14 -070072 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070073 if err != nil {
74 return err
75 }
76 if err := f(gen); err != nil {
77 // Errors from the plugin function are reported by setting the
78 // error field in the CodeGeneratorResponse.
79 //
80 // In contrast, errors that indicate a problem in protoc
81 // itself (unparsable input, I/O errors, etc.) are reported
82 // to stderr.
83 gen.Error(err)
84 }
85 resp := gen.Response()
86 out, err := proto.Marshal(resp)
87 if err != nil {
88 return err
89 }
90 if _, err := os.Stdout.Write(out); err != nil {
91 return err
92 }
93 return nil
94}
95
96// A Plugin is a protoc plugin invocation.
97type Plugin struct {
98 // Request is the CodeGeneratorRequest provided by protoc.
99 Request *pluginpb.CodeGeneratorRequest
100
101 // Files is the set of files to generate and everything they import.
102 // Files appear in topological order, so each file appears before any
103 // file that imports it.
104 Files []*File
Joe Tsai2cec4842019-08-20 20:14:19 -0700105 FilesByPath map[string]*File
Damien Neil220c2022018-08-15 11:24:18 -0700106
Damien Neil658051b2018-09-10 12:26:21 -0700107 fileReg *protoregistry.Files
Damien Neil658051b2018-09-10 12:26:21 -0700108 enumsByName map[protoreflect.FullName]*Enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700109 messagesByName map[protoreflect.FullName]*Message
Damien Neil162c1272018-10-04 12:42:37 -0700110 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700111 pathType pathType
112 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700113 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700114 err error
Damien Neil220c2022018-08-15 11:24:18 -0700115}
116
Damien Neil3cf6e622018-09-11 13:53:14 -0700117// Options are optional parameters to New.
118type Options struct {
119 // If ParamFunc is non-nil, it will be called with each unknown
120 // generator parameter.
121 //
122 // Plugins for protoc can accept parameters from the command line,
123 // passed in the --<lang>_out protoc, separated from the output
124 // directory with a colon; e.g.,
125 //
126 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
127 //
128 // Parameters passed in this fashion as a comma-separated list of
129 // key=value pairs will be passed to the ParamFunc.
130 //
131 // The (flag.FlagSet).Set method matches this function signature,
132 // so parameters can be converted into flags as in the following:
133 //
134 // var flags flag.FlagSet
135 // value := flags.Bool("param", false, "")
136 // opts := &protogen.Options{
137 // ParamFunc: flags.Set,
138 // }
139 // protogen.Run(opts, func(p *protogen.Plugin) error {
140 // if *value { ... }
141 // })
142 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700143
144 // ImportRewriteFunc is called with the import path of each package
145 // imported by a generated file. It returns the import path to use
146 // for this package.
147 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700148}
149
Damien Neil220c2022018-08-15 11:24:18 -0700150// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700151//
152// Passing a nil Options is equivalent to passing a zero-valued one.
153func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
154 if opts == nil {
155 opts = &Options{}
156 }
Damien Neil220c2022018-08-15 11:24:18 -0700157 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700158 Request: req,
Joe Tsai2cec4842019-08-20 20:14:19 -0700159 FilesByPath: make(map[string]*File),
Damien Neilc8268852019-10-08 13:28:53 -0700160 fileReg: new(protoregistry.Files),
Damien Neil658051b2018-09-10 12:26:21 -0700161 enumsByName: make(map[protoreflect.FullName]*Enum),
Joe Tsai7762ec22019-08-20 20:10:23 -0700162 messagesByName: make(map[protoreflect.FullName]*Message),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700163 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700164 }
165
Damien Neil082ce922018-09-06 10:23:53 -0700166 packageNames := make(map[string]GoPackageName) // filename -> package name
167 importPaths := make(map[string]GoImportPath) // filename -> import path
Joe Tsai3e802492019-09-07 13:06:27 -0700168 mfiles := make(map[string]bool) // filename set
Damien Neil082ce922018-09-06 10:23:53 -0700169 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700170 for _, param := range strings.Split(req.GetParameter(), ",") {
171 var value string
172 if i := strings.Index(param, "="); i >= 0 {
173 value = param[i+1:]
174 param = param[0:i]
175 }
176 switch param {
177 case "":
178 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700179 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700180 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700181 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700182 switch value {
183 case "import":
184 gen.pathType = pathTypeImport
185 case "source_relative":
186 gen.pathType = pathTypeSourceRelative
187 default:
188 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
189 }
Damien Neil220c2022018-08-15 11:24:18 -0700190 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700191 switch value {
192 case "true", "":
193 gen.annotateCode = true
194 case "false":
195 default:
196 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
197 }
Damien Neil220c2022018-08-15 11:24:18 -0700198 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700199 if param[0] == 'M' {
200 importPaths[param[1:]] = GoImportPath(value)
Joe Tsai3e802492019-09-07 13:06:27 -0700201 mfiles[param[1:]] = true
Damien Neil3cf6e622018-09-11 13:53:14 -0700202 continue
Damien Neil220c2022018-08-15 11:24:18 -0700203 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700204 if opts.ParamFunc != nil {
205 if err := opts.ParamFunc(param, value); err != nil {
206 return nil, err
207 }
208 }
Damien Neil082ce922018-09-06 10:23:53 -0700209 }
210 }
211
212 // Figure out the import path and package name for each file.
213 //
214 // The rules here are complicated and have grown organically over time.
215 // Interactions between different ways of specifying package information
216 // may be surprising.
217 //
218 // The recommended approach is to include a go_package option in every
219 // .proto source file specifying the full import path of the Go package
220 // associated with this file.
221 //
Joe Tsai8d30bbe2019-05-16 15:53:25 -0700222 // option go_package = "google.golang.org/protobuf/types/known/anypb";
Damien Neil082ce922018-09-06 10:23:53 -0700223 //
224 // Build systems which want to exert full control over import paths may
225 // specify M<filename>=<import_path> flags.
226 //
227 // Other approaches are not recommend.
228 generatedFileNames := make(map[string]bool)
229 for _, name := range gen.Request.FileToGenerate {
230 generatedFileNames[name] = true
231 }
232 // We need to determine the import paths before the package names,
233 // because the Go package name for a file is sometimes derived from
234 // different file in the same package.
235 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
236 for _, fdesc := range gen.Request.ProtoFile {
237 filename := fdesc.GetName()
238 packageName, importPath := goPackageOption(fdesc)
239 switch {
240 case importPaths[filename] != "":
241 // Command line: M=foo.proto=quux/bar
242 //
243 // Explicit mapping of source file to import path.
244 case generatedFileNames[filename] && packageImportPath != "":
245 // Command line: import_path=quux/bar
246 //
247 // The import_path flag sets the import path for every file that
248 // we generate code for.
249 importPaths[filename] = packageImportPath
250 case importPath != "":
251 // Source file: option go_package = "quux/bar";
252 //
253 // The go_package option sets the import path. Most users should use this.
254 importPaths[filename] = importPath
255 default:
256 // Source filename.
257 //
258 // Last resort when nothing else is available.
259 importPaths[filename] = GoImportPath(path.Dir(filename))
260 }
261 if packageName != "" {
262 packageNameForImportPath[importPaths[filename]] = packageName
263 }
264 }
265 for _, fdesc := range gen.Request.ProtoFile {
266 filename := fdesc.GetName()
Joe Tsai3e802492019-09-07 13:06:27 -0700267 packageName, importPath := goPackageOption(fdesc)
Damien Neil082ce922018-09-06 10:23:53 -0700268 defaultPackageName := packageNameForImportPath[importPaths[filename]]
269 switch {
270 case packageName != "":
Joe Tsai3e802492019-09-07 13:06:27 -0700271 // TODO: For the "M" command-line argument, this means that the
272 // package name can be derived from the go_package option.
273 // Go package information should either consistently come from the
274 // command-line or the .proto source file, but not both.
275 // See how to make this consistent.
276
Damien Neil082ce922018-09-06 10:23:53 -0700277 // Source file: option go_package = "quux/bar";
278 packageNames[filename] = packageName
279 case defaultPackageName != "":
280 // A go_package option in another file in the same package.
281 //
282 // This is a poor choice in general, since every source file should
283 // contain a go_package option. Supported mainly for historical
284 // compatibility.
285 packageNames[filename] = defaultPackageName
286 case generatedFileNames[filename] && packageImportPath != "":
287 // Command line: import_path=quux/bar
288 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
289 case fdesc.GetPackage() != "":
290 // Source file: package quux.bar;
291 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
292 default:
293 // Source filename.
294 packageNames[filename] = cleanPackageName(baseName(filename))
295 }
Joe Tsai3e802492019-09-07 13:06:27 -0700296
297 goPkgOpt := string(importPaths[filename])
298 if path.Base(string(goPkgOpt)) != string(packageNames[filename]) {
299 goPkgOpt += ";" + string(packageNames[filename])
300 }
301 switch {
302 case packageImportPath != "":
303 // Command line: import_path=quux/bar
304 log.Printf("WARNING: Deprecated use of the 'import_path' command-line argument. In %q, please specify:\n"+
305 "\toption go_package = %q;\n"+
306 "A future release of protoc-gen-go will no longer support the 'import_path' argument.\n"+
307 "\n", fdesc.GetName(), goPkgOpt)
308 case mfiles[filename]:
309 // Command line: M=foo.proto=quux/bar
310 case packageName != "" && importPath == "":
311 // Source file: option go_package = "quux";
312 log.Printf("WARNING: Deprecated use of 'go_package' option without a full import path in %q, please specify:\n"+
313 "\toption go_package = %q;\n"+
314 "A future release of protoc-gen-go will require the import path be specified.\n"+
315 "\n", fdesc.GetName(), goPkgOpt)
316 case packageName == "" && importPath == "":
317 // No Go package information provided.
318 log.Printf("WARNING: Missing 'go_package' option in %q, please specify:\n"+
319 "\toption go_package = %q;\n"+
320 "A future release of protoc-gen-go will require this be specified.\n"+
321 "\n", fdesc.GetName(), goPkgOpt)
322 }
Damien Neil082ce922018-09-06 10:23:53 -0700323 }
324
325 // Consistency check: Every file with the same Go import path should have
326 // the same Go package name.
327 packageFiles := make(map[GoImportPath][]string)
328 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700329 if _, ok := packageNames[filename]; !ok {
330 // Skip files mentioned in a M<file>=<import_path> parameter
331 // but which do not appear in the CodeGeneratorRequest.
332 continue
333 }
Damien Neil082ce922018-09-06 10:23:53 -0700334 packageFiles[importPath] = append(packageFiles[importPath], filename)
335 }
336 for importPath, filenames := range packageFiles {
337 for i := 1; i < len(filenames); i++ {
338 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
339 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
340 importPath, a, filenames[0], b, filenames[i])
341 }
Damien Neil220c2022018-08-15 11:24:18 -0700342 }
343 }
344
345 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700346 filename := fdesc.GetName()
Joe Tsai2cec4842019-08-20 20:14:19 -0700347 if gen.FilesByPath[filename] != nil {
Damien Neil082ce922018-09-06 10:23:53 -0700348 return nil, fmt.Errorf("duplicate file name: %q", filename)
349 }
350 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700351 if err != nil {
352 return nil, err
353 }
Damien Neil220c2022018-08-15 11:24:18 -0700354 gen.Files = append(gen.Files, f)
Joe Tsai2cec4842019-08-20 20:14:19 -0700355 gen.FilesByPath[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700356 }
Damien Neil082ce922018-09-06 10:23:53 -0700357 for _, filename := range gen.Request.FileToGenerate {
Joe Tsai2cec4842019-08-20 20:14:19 -0700358 f, ok := gen.FilesByPath[filename]
Damien Neil220c2022018-08-15 11:24:18 -0700359 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700360 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700361 }
362 f.Generate = true
363 }
364 return gen, nil
365}
366
367// Error records an error in code generation. The generator will report the
368// error back to protoc and will not produce output.
369func (gen *Plugin) Error(err error) {
370 if gen.err == nil {
371 gen.err = err
372 }
373}
374
375// Response returns the generator output.
376func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
377 resp := &pluginpb.CodeGeneratorResponse{}
378 if gen.err != nil {
Damien Neila8a2cea2019-07-10 16:17:16 -0700379 resp.Error = proto.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700380 return resp
381 }
Damien Neil162c1272018-10-04 12:42:37 -0700382 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800383 if g.skip {
384 continue
385 }
386 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700387 if err != nil {
388 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700389 Error: proto.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700390 }
391 }
Damien Neil220c2022018-08-15 11:24:18 -0700392 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700393 Name: proto.String(g.filename),
394 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700395 })
Damien Neil162c1272018-10-04 12:42:37 -0700396 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
397 meta, err := g.metaFile(content)
398 if err != nil {
399 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700400 Error: proto.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700401 }
402 }
403 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700404 Name: proto.String(g.filename + ".meta"),
405 Content: proto.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700406 })
407 }
Damien Neil220c2022018-08-15 11:24:18 -0700408 }
409 return resp
410}
411
Damien Neilc7d07d92018-08-22 13:46:02 -0700412// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700413type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700414 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800415 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700416
Joe Tsaib6405bd2018-11-15 14:44:37 -0800417 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
418 GoPackageName GoPackageName // name of this file's Go package
419 GoImportPath GoImportPath // import path of this file's Go package
Joe Tsai7762ec22019-08-20 20:10:23 -0700420
421 Enums []*Enum // top-level enum declarations
422 Messages []*Message // top-level message declarations
423 Extensions []*Extension // top-level extension declarations
424 Services []*Service // top-level service declarations
425
426 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700427
428 // GeneratedFilenamePrefix is used to construct filenames for generated
429 // files associated with this source file.
430 //
431 // For example, the source file "dir/foo.proto" might have a filename prefix
432 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
433 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700434
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700435 comments map[pathKey]CommentSet
Damien Neil220c2022018-08-15 11:24:18 -0700436}
437
Joe Tsaie1f8d502018-11-26 18:55:29 -0800438func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
439 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700440 if err != nil {
441 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
442 }
Damien Neilc8268852019-10-08 13:28:53 -0700443 if err := gen.fileReg.RegisterFile(desc); err != nil {
Damien Neilabc6fc12018-08-23 14:39:30 -0700444 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
445 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700446 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700447 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700448 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700449 GoPackageName: packageName,
450 GoImportPath: importPath,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700451 comments: make(map[pathKey]CommentSet),
Damien Neil220c2022018-08-15 11:24:18 -0700452 }
Damien Neil082ce922018-09-06 10:23:53 -0700453
454 // Determine the prefix for generated Go files.
455 prefix := p.GetName()
456 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
457 prefix = prefix[:len(prefix)-len(ext)]
458 }
459 if gen.pathType == pathTypeImport {
460 // If paths=import (the default) and the file contains a go_package option
461 // with a full import path, the output filename is derived from the Go import
462 // path.
463 //
464 // Pass the paths=source_relative flag to always derive the output filename
465 // from the input filename instead.
466 if _, importPath := goPackageOption(p); importPath != "" {
467 prefix = path.Join(string(importPath), path.Base(prefix))
468 }
469 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800470 f.GoDescriptorIdent = GoIdent{
Joe Tsai2e7817f2019-08-23 12:18:57 -0700471 GoName: "File_" + strs.GoSanitized(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800472 GoImportPath: f.GoImportPath,
473 }
Damien Neil082ce922018-09-06 10:23:53 -0700474 f.GeneratedFilenamePrefix = prefix
475
Damien Neilba1159f2018-10-17 12:53:18 -0700476 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700477 // Descriptors declarations are guaranteed to have unique comment sets.
478 // Other locations may not be unique, but we don't use them.
479 var leadingDetached []Comments
480 for _, s := range loc.GetLeadingDetachedComments() {
481 leadingDetached = append(leadingDetached, Comments(s))
482 }
483 f.comments[newPathKey(loc.Path)] = CommentSet{
484 LeadingDetached: leadingDetached,
485 Leading: Comments(loc.GetLeadingComments()),
486 Trailing: Comments(loc.GetTrailingComments()),
487 }
Damien Neilba1159f2018-10-17 12:53:18 -0700488 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700489 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
490 f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700491 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700492 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
493 f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700494 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700495 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
496 f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
Damien Neil993c04d2018-09-14 15:41:11 -0700497 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700498 for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
499 f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700500 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700501 for _, message := range f.Messages {
Joe Tsai7762ec22019-08-20 20:10:23 -0700502 if err := message.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700503 return nil, err
504 }
505 }
506 for _, extension := range f.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700507 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700508 return nil, err
509 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700510 }
Damien Neil2dc67182018-09-21 15:03:34 -0700511 for _, service := range f.Services {
512 for _, method := range service.Methods {
Joe Tsai7762ec22019-08-20 20:10:23 -0700513 if err := method.resolveDependencies(gen); err != nil {
Damien Neil2dc67182018-09-21 15:03:34 -0700514 return nil, err
515 }
516 }
517 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700518 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700519}
520
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900521func (f *File) location(idxPath ...int32) Location {
Damien Neil162c1272018-10-04 12:42:37 -0700522 return Location{
523 SourceFile: f.Desc.Path(),
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900524 Path: idxPath,
Damien Neil162c1272018-10-04 12:42:37 -0700525 }
526}
527
Damien Neil082ce922018-09-06 10:23:53 -0700528// goPackageOption interprets a file's go_package option.
529// If there is no go_package, it returns ("", "").
530// If there's a simple name, it returns (pkg, "").
531// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800532func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700533 opt := d.GetOptions().GetGoPackage()
534 if opt == "" {
535 return "", ""
536 }
Joe Tsai3e802492019-09-07 13:06:27 -0700537 rawPkg, impPath := goPackageOptionRaw(opt)
538 pkg = cleanPackageName(rawPkg)
539 if string(pkg) != rawPkg && impPath != "" {
540 log.Printf("WARNING: Malformed 'go_package' option in %q, please specify:\n"+
541 "\toption go_package = %q;\n"+
542 "A future release of protoc-gen-go will reject this.\n"+
543 "\n", d.GetName(), string(impPath)+";"+string(pkg))
544 }
545 return pkg, impPath
546}
547func goPackageOptionRaw(opt string) (rawPkg string, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700548 // A semicolon-delimited suffix delimits the import path and package name.
549 if i := strings.Index(opt, ";"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700550 return opt[i+1:], GoImportPath(opt[:i])
Damien Neil082ce922018-09-06 10:23:53 -0700551 }
552 // The presence of a slash implies there's an import path.
553 if i := strings.LastIndex(opt, "/"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700554 return opt[i+1:], GoImportPath(opt)
Damien Neil082ce922018-09-06 10:23:53 -0700555 }
Joe Tsai3e802492019-09-07 13:06:27 -0700556 return opt, ""
Damien Neil082ce922018-09-06 10:23:53 -0700557}
558
Joe Tsai7762ec22019-08-20 20:10:23 -0700559// An Enum describes an enum.
560type Enum struct {
561 Desc protoreflect.EnumDescriptor
562
563 GoIdent GoIdent // name of the generated Go type
564
565 Values []*EnumValue // enum value declarations
566
567 Location Location // location of this enum
568 Comments CommentSet // comments associated with this enum
569}
570
571func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
572 var loc Location
573 if parent != nil {
574 loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index()))
575 } else {
576 loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index()))
577 }
578 enum := &Enum{
579 Desc: desc,
580 GoIdent: newGoIdent(f, desc),
581 Location: loc,
582 Comments: f.comments[newPathKey(loc.Path)],
583 }
584 gen.enumsByName[desc.FullName()] = enum
585 for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
586 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
587 }
588 return enum
589}
590
591// An EnumValue describes an enum value.
592type EnumValue struct {
593 Desc protoreflect.EnumValueDescriptor
594
595 GoIdent GoIdent // name of the generated Go declaration
596
Joe Tsai4df99fd2019-08-20 22:26:16 -0700597 Parent *Enum // enum in which this value is declared
598
Joe Tsai7762ec22019-08-20 20:10:23 -0700599 Location Location // location of this enum value
600 Comments CommentSet // comments associated with this enum value
601}
602
603func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
604 // A top-level enum value's name is: EnumName_ValueName
605 // An enum value contained in a message is: MessageName_ValueName
606 //
Joe Tsaief6e5242019-08-21 00:55:36 -0700607 // For historical reasons, enum value names are not camel-cased.
Joe Tsai7762ec22019-08-20 20:10:23 -0700608 parentIdent := enum.GoIdent
609 if message != nil {
610 parentIdent = message.GoIdent
611 }
612 name := parentIdent.GoName + "_" + string(desc.Name())
613 loc := enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index()))
614 return &EnumValue{
615 Desc: desc,
616 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai4df99fd2019-08-20 22:26:16 -0700617 Parent: enum,
Joe Tsai7762ec22019-08-20 20:10:23 -0700618 Location: loc,
619 Comments: f.comments[newPathKey(loc.Path)],
620 }
621}
622
Damien Neilc7d07d92018-08-22 13:46:02 -0700623// A Message describes a message.
624type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700625 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700626
Joe Tsai7762ec22019-08-20 20:10:23 -0700627 GoIdent GoIdent // name of the generated Go type
628
629 Fields []*Field // message field declarations
630 Oneofs []*Oneof // message oneof declarations
631
Damien Neil993c04d2018-09-14 15:41:11 -0700632 Enums []*Enum // nested enum declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700633 Messages []*Message // nested message declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700634 Extensions []*Extension // nested extension declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700635
636 Location Location // location of this message
637 Comments CommentSet // comments associated with this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700638}
639
Damien Neil1fa78d82018-09-13 13:12:36 -0700640func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700641 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700642 if parent != nil {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700643 loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700644 } else {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700645 loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700646 }
Damien Neil46abb572018-09-07 12:45:37 -0700647 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700648 Desc: desc,
649 GoIdent: newGoIdent(f, desc),
650 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700651 Comments: f.comments[newPathKey(loc.Path)],
Damien Neilc7d07d92018-08-22 13:46:02 -0700652 }
Damien Neil658051b2018-09-10 12:26:21 -0700653 gen.messagesByName[desc.FullName()] = message
Joe Tsai7762ec22019-08-20 20:10:23 -0700654 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
655 message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700656 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700657 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
658 message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700659 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700660 for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
661 message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
Damien Neil1fa78d82018-09-13 13:12:36 -0700662 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700663 for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
664 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700665 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700666 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
667 message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
668 }
669
670 // Resolve local references between fields and oneofs.
671 for _, field := range message.Fields {
672 if od := field.Desc.ContainingOneof(); od != nil {
673 oneof := message.Oneofs[od.Index()]
674 field.Oneof = oneof
675 oneof.Fields = append(oneof.Fields, field)
676 }
Damien Neil993c04d2018-09-14 15:41:11 -0700677 }
Damien Neil658051b2018-09-10 12:26:21 -0700678
679 // Field name conflict resolution.
680 //
681 // We assume well-known method names that may be attached to a generated
682 // message type, as well as a 'Get*' method for each field. For each
683 // field in turn, we add _s to its name until there are no conflicts.
684 //
685 // Any change to the following set of method names is a potential
686 // incompatible API change because it may change generated field names.
687 //
688 // TODO: If we ever support a 'go_name' option to set the Go name of a
689 // field, we should consider dropping this entirely. The conflict
690 // resolution algorithm is subtle and surprising (changing the order
691 // in which fields appear in the .proto source file can change the
692 // names of fields in generated code), and does not adapt well to
693 // adding new per-field methods such as setters.
694 usedNames := map[string]bool{
695 "Reset": true,
696 "String": true,
697 "ProtoMessage": true,
698 "Marshal": true,
699 "Unmarshal": true,
700 "ExtensionRangeArray": true,
701 "ExtensionMap": true,
702 "Descriptor": true,
703 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800704 makeNameUnique := func(name string, hasGetter bool) string {
705 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700706 name += "_"
707 }
708 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800709 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700710 return name
711 }
712 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800713 field.GoName = makeNameUnique(field.GoName, true)
Joe Tsaief6e5242019-08-21 00:55:36 -0700714 field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName
715 if field.Oneof != nil && field.Oneof.Fields[0] == field {
716 // Make the name for a oneof unique as well. For historical reasons,
717 // this assumes that a getter method is not generated for oneofs.
718 // This is incorrect, but fixing it breaks existing code.
719 field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
720 field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName
721 }
722 }
723
724 // Oneof field name conflict resolution.
725 //
726 // This conflict resolution is incomplete as it does not consider collisions
727 // with other oneof field types, but fixing it breaks existing code.
728 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700729 if field.Oneof != nil {
Joe Tsaief6e5242019-08-21 00:55:36 -0700730 Loop:
731 for {
732 for _, nestedMessage := range message.Messages {
733 if nestedMessage.GoIdent == field.GoIdent {
734 field.GoIdent.GoName += "_"
735 continue Loop
736 }
737 }
738 for _, nestedEnum := range message.Enums {
739 if nestedEnum.GoIdent == field.GoIdent {
740 field.GoIdent.GoName += "_"
741 continue Loop
742 }
743 }
744 break Loop
Damien Neil1fa78d82018-09-13 13:12:36 -0700745 }
746 }
Damien Neil658051b2018-09-10 12:26:21 -0700747 }
748
Damien Neil1fa78d82018-09-13 13:12:36 -0700749 return message
Damien Neil658051b2018-09-10 12:26:21 -0700750}
751
Joe Tsai7762ec22019-08-20 20:10:23 -0700752func (message *Message) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700753 for _, field := range message.Fields {
Joe Tsai7762ec22019-08-20 20:10:23 -0700754 if err := field.resolveDependencies(gen); err != nil {
Damien Neil0bd5a382018-09-13 15:07:10 -0700755 return err
756 }
757 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700758 for _, message := range message.Messages {
759 if err := message.resolveDependencies(gen); err != nil {
760 return err
761 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700762 }
Damien Neil993c04d2018-09-14 15:41:11 -0700763 for _, extension := range message.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700764 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700765 return err
766 }
767 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700768 return nil
769}
770
Damien Neil658051b2018-09-10 12:26:21 -0700771// A Field describes a message field.
772type Field struct {
773 Desc protoreflect.FieldDescriptor
774
Damien Neil1fa78d82018-09-13 13:12:36 -0700775 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700776 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700777 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
Joe Tsaief6e5242019-08-21 00:55:36 -0700778 GoName string // e.g., "FieldName"
779
780 // GoIdent is the base name of a top-level declaration for this field.
781 // For code generated by protoc-gen-go, this means a wrapper type named
782 // '{{GoIdent}}' for members fields of a oneof, and a variable named
783 // 'E_{{GoIdent}}' for extension fields.
784 GoIdent GoIdent // e.g., "MessageName_FieldName"
Damien Neil658051b2018-09-10 12:26:21 -0700785
Joe Tsai7762ec22019-08-20 20:10:23 -0700786 Parent *Message // message in which this field is declared; nil if top-level extension
787 Oneof *Oneof // containing oneof; nil if not part of a oneof
788 Extendee *Message // extended message for extension fields; nil otherwise
789
790 Enum *Enum // type for enum fields; nil otherwise
791 Message *Message // type for message or group fields; nil otherwise
792
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700793 Location Location // location of this field
794 Comments CommentSet // comments associated with this field
Damien Neil658051b2018-09-10 12:26:21 -0700795}
796
Damien Neil1fa78d82018-09-13 13:12:36 -0700797func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700798 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700799 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700800 case desc.IsExtension() && message == nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700801 loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index()))
Joe Tsaiac31a352019-05-13 14:32:56 -0700802 case desc.IsExtension() && message != nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700803 loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700804 default:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700805 loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700806 }
Joe Tsai2e7817f2019-08-23 12:18:57 -0700807 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700808 var parentPrefix string
809 if message != nil {
810 parentPrefix = message.GoIdent.GoName + "_"
811 }
Damien Neil658051b2018-09-10 12:26:21 -0700812 field := &Field{
Joe Tsaief6e5242019-08-21 00:55:36 -0700813 Desc: desc,
814 GoName: camelCased,
815 GoIdent: GoIdent{
816 GoImportPath: f.GoImportPath,
817 GoName: parentPrefix + camelCased,
818 },
Joe Tsaid24bc722019-04-15 23:39:09 -0700819 Parent: message,
820 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700821 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil658051b2018-09-10 12:26:21 -0700822 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700823 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700824}
825
Joe Tsai7762ec22019-08-20 20:10:23 -0700826func (field *Field) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700827 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700828 switch desc.Kind() {
Damien Neil658051b2018-09-10 12:26:21 -0700829 case protoreflect.EnumKind:
Joe Tsai7762ec22019-08-20 20:10:23 -0700830 name := field.Desc.Enum().FullName()
831 enum, ok := gen.enumsByName[name]
Damien Neil658051b2018-09-10 12:26:21 -0700832 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700833 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
Damien Neil658051b2018-09-10 12:26:21 -0700834 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700835 field.Enum = enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700836 case protoreflect.MessageKind, protoreflect.GroupKind:
837 name := desc.Message().FullName()
838 message, ok := gen.messagesByName[name]
839 if !ok {
840 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
841 }
842 field.Message = message
Damien Neil658051b2018-09-10 12:26:21 -0700843 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700844 if desc.IsExtension() {
Joe Tsai7762ec22019-08-20 20:10:23 -0700845 name := desc.ContainingMessage().FullName()
846 message, ok := gen.messagesByName[name]
Damien Neil993c04d2018-09-14 15:41:11 -0700847 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700848 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
Damien Neil993c04d2018-09-14 15:41:11 -0700849 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700850 field.Extendee = message
Damien Neil993c04d2018-09-14 15:41:11 -0700851 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700852 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700853}
854
Joe Tsai7762ec22019-08-20 20:10:23 -0700855// A Oneof describes a message oneof.
Damien Neil1fa78d82018-09-13 13:12:36 -0700856type Oneof struct {
857 Desc protoreflect.OneofDescriptor
858
Joe Tsaief6e5242019-08-21 00:55:36 -0700859 // GoName is the base name of this oneof's Go field and methods.
860 // For code generated by protoc-gen-go, this means a field named
861 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
862 GoName string // e.g., "OneofName"
863
864 // GoIdent is the base name of a top-level declaration for this oneof.
865 GoIdent GoIdent // e.g., "MessageName_OneofName"
Joe Tsai7762ec22019-08-20 20:10:23 -0700866
867 Parent *Message // message in which this oneof is declared
868
Joe Tsaid24bc722019-04-15 23:39:09 -0700869 Fields []*Field // fields that are part of this oneof
870
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700871 Location Location // location of this oneof
872 Comments CommentSet // comments associated with this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700873}
874
875func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700876 loc := message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index()))
Joe Tsai2e7817f2019-08-23 12:18:57 -0700877 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700878 parentPrefix := message.GoIdent.GoName + "_"
Damien Neil1fa78d82018-09-13 13:12:36 -0700879 return &Oneof{
Joe Tsaief6e5242019-08-21 00:55:36 -0700880 Desc: desc,
881 Parent: message,
882 GoName: camelCased,
883 GoIdent: GoIdent{
884 GoImportPath: f.GoImportPath,
885 GoName: parentPrefix + camelCased,
886 },
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700887 Location: loc,
888 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil1fa78d82018-09-13 13:12:36 -0700889 }
890}
891
Joe Tsai7762ec22019-08-20 20:10:23 -0700892// Extension is an alias of Field for documentation.
893type Extension = Field
Damien Neil220c2022018-08-15 11:24:18 -0700894
Damien Neil2dc67182018-09-21 15:03:34 -0700895// A Service describes a service.
896type Service struct {
897 Desc protoreflect.ServiceDescriptor
898
Joe Tsai7762ec22019-08-20 20:10:23 -0700899 GoName string
900
901 Methods []*Method // service method declarations
Joe Tsaid24bc722019-04-15 23:39:09 -0700902
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700903 Location Location // location of this service
904 Comments CommentSet // comments associated with this service
Damien Neil2dc67182018-09-21 15:03:34 -0700905}
906
907func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700908 loc := f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700909 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700910 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700911 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700912 Location: loc,
913 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700914 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700915 for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
916 service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700917 }
918 return service
919}
920
921// A Method describes a method in a service.
922type Method struct {
923 Desc protoreflect.MethodDescriptor
924
Joe Tsaid24bc722019-04-15 23:39:09 -0700925 GoName string
Joe Tsai7762ec22019-08-20 20:10:23 -0700926
927 Parent *Service // service in which this method is declared
928
Joe Tsaid24bc722019-04-15 23:39:09 -0700929 Input *Message
930 Output *Message
931
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700932 Location Location // location of this method
933 Comments CommentSet // comments associated with this method
Damien Neil2dc67182018-09-21 15:03:34 -0700934}
935
936func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700937 loc := service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700938 method := &Method{
Joe Tsaid24bc722019-04-15 23:39:09 -0700939 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700940 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsaid24bc722019-04-15 23:39:09 -0700941 Parent: service,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700942 Location: loc,
943 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700944 }
945 return method
946}
947
Joe Tsai7762ec22019-08-20 20:10:23 -0700948func (method *Method) resolveDependencies(gen *Plugin) error {
Damien Neil2dc67182018-09-21 15:03:34 -0700949 desc := method.Desc
950
Joe Tsaid24bc722019-04-15 23:39:09 -0700951 inName := desc.Input().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700952 in, ok := gen.messagesByName[inName]
953 if !ok {
954 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
955 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700956 method.Input = in
Damien Neil2dc67182018-09-21 15:03:34 -0700957
Joe Tsaid24bc722019-04-15 23:39:09 -0700958 outName := desc.Output().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700959 out, ok := gen.messagesByName[outName]
960 if !ok {
961 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
962 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700963 method.Output = out
Damien Neil2dc67182018-09-21 15:03:34 -0700964
965 return nil
966}
967
Damien Neil7bf3ce22018-12-21 15:54:06 -0800968// A GeneratedFile is a generated file.
969type GeneratedFile struct {
970 gen *Plugin
971 skip bool
972 filename string
973 goImportPath GoImportPath
974 buf bytes.Buffer
975 packageNames map[GoImportPath]GoPackageName
976 usedPackageNames map[GoPackageName]bool
977 manualImports map[GoImportPath]bool
978 annotations map[string][]Location
979}
980
981// NewGeneratedFile creates a new generated file with the given filename
982// and import path.
983func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
984 g := &GeneratedFile{
985 gen: gen,
986 filename: filename,
987 goImportPath: goImportPath,
988 packageNames: make(map[GoImportPath]GoPackageName),
989 usedPackageNames: make(map[GoPackageName]bool),
990 manualImports: make(map[GoImportPath]bool),
991 annotations: make(map[string][]Location),
992 }
Joe Tsai124c8122019-01-14 11:48:43 -0800993
994 // All predeclared identifiers in Go are already used.
995 for _, s := range types.Universe.Names() {
996 g.usedPackageNames[GoPackageName(s)] = true
997 }
998
Damien Neil7bf3ce22018-12-21 15:54:06 -0800999 gen.genFiles = append(gen.genFiles, g)
1000 return g
1001}
1002
Damien Neil220c2022018-08-15 11:24:18 -07001003// P prints a line to the generated output. It converts each parameter to a
1004// string following the same rules as fmt.Print. It never inserts spaces
1005// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -07001006func (g *GeneratedFile) P(v ...interface{}) {
1007 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -07001008 switch x := x.(type) {
1009 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -07001010 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -07001011 default:
1012 fmt.Fprint(&g.buf, x)
1013 }
Damien Neil220c2022018-08-15 11:24:18 -07001014 }
1015 fmt.Fprintln(&g.buf)
1016}
1017
Damien Neil46abb572018-09-07 12:45:37 -07001018// QualifiedGoIdent returns the string to use for a Go identifier.
1019//
1020// If the identifier is from a different Go package than the generated file,
1021// the returned name will be qualified (package.name) and an import statement
1022// for the identifier's package will be included in the file.
1023func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
1024 if ident.GoImportPath == g.goImportPath {
1025 return ident.GoName
1026 }
1027 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
1028 return string(packageName) + "." + ident.GoName
1029 }
1030 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -08001031 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -07001032 packageName = orig + GoPackageName(strconv.Itoa(i))
1033 }
1034 g.packageNames[ident.GoImportPath] = packageName
1035 g.usedPackageNames[packageName] = true
1036 return string(packageName) + "." + ident.GoName
1037}
1038
Damien Neil2e0c3da2018-09-19 12:51:36 -07001039// Import ensures a package is imported by the generated file.
1040//
1041// Packages referenced by QualifiedGoIdent are automatically imported.
1042// Explicitly importing a package with Import is generally only necessary
1043// when the import will be blank (import _ "package").
1044func (g *GeneratedFile) Import(importPath GoImportPath) {
1045 g.manualImports[importPath] = true
1046}
1047
Damien Neil220c2022018-08-15 11:24:18 -07001048// Write implements io.Writer.
1049func (g *GeneratedFile) Write(p []byte) (n int, err error) {
1050 return g.buf.Write(p)
1051}
1052
Damien Neil7bf3ce22018-12-21 15:54:06 -08001053// Skip removes the generated file from the plugin output.
1054func (g *GeneratedFile) Skip() {
1055 g.skip = true
1056}
1057
Damien Neil162c1272018-10-04 12:42:37 -07001058// Annotate associates a symbol in a generated Go file with a location in a
1059// source .proto file.
1060//
1061// The symbol may refer to a type, constant, variable, function, method, or
1062// struct field. The "T.sel" syntax is used to identify the method or field
1063// 'sel' on type 'T'.
1064func (g *GeneratedFile) Annotate(symbol string, loc Location) {
1065 g.annotations[symbol] = append(g.annotations[symbol], loc)
1066}
1067
Damien Neil7bf3ce22018-12-21 15:54:06 -08001068// Content returns the contents of the generated file.
1069func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -07001070 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -07001071 return g.buf.Bytes(), nil
1072 }
1073
1074 // Reformat generated code.
1075 original := g.buf.Bytes()
1076 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -07001077 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -07001078 if err != nil {
1079 // Print out the bad code with line numbers.
1080 // This should never happen in practice, but it can while changing generated code
1081 // so consider this a debugging aid.
1082 var src bytes.Buffer
1083 s := bufio.NewScanner(bytes.NewReader(original))
1084 for line := 1; s.Scan(); line++ {
1085 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
1086 }
Damien Neild9016772018-08-23 14:39:30 -07001087 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -07001088 }
Damien Neild9016772018-08-23 14:39:30 -07001089
Joe Tsaibeda4042019-03-10 16:40:48 -07001090 // Collect a sorted list of all imports.
1091 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -07001092 rewriteImport := func(importPath string) string {
1093 if f := g.gen.opts.ImportRewriteFunc; f != nil {
1094 return string(f(GoImportPath(importPath)))
1095 }
1096 return importPath
1097 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001098 for importPath := range g.packageNames {
1099 pkgName := string(g.packageNames[GoImportPath(importPath)])
1100 pkgPath := rewriteImport(string(importPath))
1101 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -07001102 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001103 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -07001104 if _, ok := g.packageNames[importPath]; !ok {
1105 pkgPath := rewriteImport(string(importPath))
1106 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -07001107 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001108 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001109 sort.Slice(importPaths, func(i, j int) bool {
1110 return importPaths[i][1] < importPaths[j][1]
1111 })
1112
1113 // Modify the AST to include a new import block.
1114 if len(importPaths) > 0 {
1115 // Insert block after package statement or
1116 // possible comment attached to the end of the package statement.
1117 pos := file.Package
1118 tokFile := fset.File(file.Package)
1119 pkgLine := tokFile.Line(file.Package)
1120 for _, c := range file.Comments {
1121 if tokFile.Line(c.Pos()) > pkgLine {
1122 break
1123 }
1124 pos = c.End()
1125 }
1126
1127 // Construct the import block.
1128 impDecl := &ast.GenDecl{
1129 Tok: token.IMPORT,
1130 TokPos: pos,
1131 Lparen: pos,
1132 Rparen: pos,
1133 }
1134 for _, importPath := range importPaths {
1135 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1136 Name: &ast.Ident{
1137 Name: importPath[0],
1138 NamePos: pos,
1139 },
1140 Path: &ast.BasicLit{
1141 Kind: token.STRING,
1142 Value: strconv.Quote(importPath[1]),
1143 ValuePos: pos,
1144 },
1145 EndPos: pos,
1146 })
1147 }
1148 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1149 }
Damien Neild9016772018-08-23 14:39:30 -07001150
Damien Neilc7d07d92018-08-22 13:46:02 -07001151 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001152 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001153 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001154 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001155 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001156}
Damien Neilc7d07d92018-08-22 13:46:02 -07001157
Damien Neil162c1272018-10-04 12:42:37 -07001158// metaFile returns the contents of the file's metadata file, which is a
1159// text formatted string of the google.protobuf.GeneratedCodeInfo.
1160func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1161 fset := token.NewFileSet()
1162 astFile, err := parser.ParseFile(fset, "", content, 0)
1163 if err != nil {
1164 return "", err
1165 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001166 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001167
1168 seenAnnotations := make(map[string]bool)
1169 annotate := func(s string, ident *ast.Ident) {
1170 seenAnnotations[s] = true
1171 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001172 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Damien Neila8a2cea2019-07-10 16:17:16 -07001173 SourceFile: proto.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001174 Path: loc.Path,
Damien Neila8a2cea2019-07-10 16:17:16 -07001175 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1176 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001177 })
1178 }
1179 }
1180 for _, decl := range astFile.Decls {
1181 switch decl := decl.(type) {
1182 case *ast.GenDecl:
1183 for _, spec := range decl.Specs {
1184 switch spec := spec.(type) {
1185 case *ast.TypeSpec:
1186 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001187 switch st := spec.Type.(type) {
1188 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001189 for _, field := range st.Fields.List {
1190 for _, name := range field.Names {
1191 annotate(spec.Name.Name+"."+name.Name, name)
1192 }
1193 }
Damien Neilae2a5612018-12-12 08:54:57 -08001194 case *ast.InterfaceType:
1195 for _, field := range st.Methods.List {
1196 for _, name := range field.Names {
1197 annotate(spec.Name.Name+"."+name.Name, name)
1198 }
1199 }
Damien Neil162c1272018-10-04 12:42:37 -07001200 }
1201 case *ast.ValueSpec:
1202 for _, name := range spec.Names {
1203 annotate(name.Name, name)
1204 }
1205 }
1206 }
1207 case *ast.FuncDecl:
1208 if decl.Recv == nil {
1209 annotate(decl.Name.Name, decl.Name)
1210 } else {
1211 recv := decl.Recv.List[0].Type
1212 if s, ok := recv.(*ast.StarExpr); ok {
1213 recv = s.X
1214 }
1215 if id, ok := recv.(*ast.Ident); ok {
1216 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1217 }
1218 }
1219 }
1220 }
1221 for a := range g.annotations {
1222 if !seenAnnotations[a] {
1223 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1224 }
1225 }
1226
Damien Neil5c5b5312019-05-14 12:44:37 -07001227 b, err := prototext.Marshal(info)
Joe Tsaif31bf262019-03-18 14:54:34 -07001228 if err != nil {
1229 return "", err
1230 }
1231 return string(b), nil
Damien Neil220c2022018-08-15 11:24:18 -07001232}
Damien Neil082ce922018-09-06 10:23:53 -07001233
Joe Tsai2e7817f2019-08-23 12:18:57 -07001234// A GoIdent is a Go identifier, consisting of a name and import path.
1235// The name is a single identifier and may not be a dot-qualified selector.
1236type GoIdent struct {
1237 GoName string
1238 GoImportPath GoImportPath
1239}
1240
1241func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
1242
1243// newGoIdent returns the Go identifier for a descriptor.
1244func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
1245 name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
1246 return GoIdent{
1247 GoName: strs.GoCamelCase(name),
1248 GoImportPath: f.GoImportPath,
1249 }
1250}
1251
1252// A GoImportPath is the import path of a Go package.
1253// For example: "google.golang.org/protobuf/compiler/protogen"
1254type GoImportPath string
1255
1256func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
1257
1258// Ident returns a GoIdent with s as the GoName and p as the GoImportPath.
1259func (p GoImportPath) Ident(s string) GoIdent {
1260 return GoIdent{GoName: s, GoImportPath: p}
1261}
1262
1263// A GoPackageName is the name of a Go package. e.g., "protobuf".
1264type GoPackageName string
1265
1266// cleanPackageName converts a string to a valid Go package name.
1267func cleanPackageName(name string) GoPackageName {
1268 return GoPackageName(strs.GoSanitized(name))
1269}
1270
1271// baseName returns the last path element of the name, with the last dotted suffix removed.
1272func baseName(name string) string {
1273 // First, find the last element
1274 if i := strings.LastIndex(name, "/"); i >= 0 {
1275 name = name[i+1:]
1276 }
1277 // Now drop the suffix
1278 if i := strings.LastIndex(name, "."); i >= 0 {
1279 name = name[:i]
1280 }
1281 return name
1282}
1283
Damien Neil082ce922018-09-06 10:23:53 -07001284type pathType int
1285
1286const (
1287 pathTypeImport pathType = iota
1288 pathTypeSourceRelative
1289)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001290
Damien Neil162c1272018-10-04 12:42:37 -07001291// A Location is a location in a .proto source file.
1292//
1293// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1294// for details.
1295type Location struct {
1296 SourceFile string
Joe Tsai691d8562019-07-12 17:16:36 -07001297 Path protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001298}
1299
1300// appendPath add elements to a Location's path, returning a new Location.
1301func (loc Location) appendPath(a ...int32) Location {
Joe Tsai691d8562019-07-12 17:16:36 -07001302 var n protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001303 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001304 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001305 return Location{
1306 SourceFile: loc.SourceFile,
1307 Path: n,
1308 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001309}
Damien Neilba1159f2018-10-17 12:53:18 -07001310
1311// A pathKey is a representation of a location path suitable for use as a map key.
1312type pathKey struct {
1313 s string
1314}
1315
1316// newPathKey converts a location path to a pathKey.
Koichi Shiraishiea2076d2019-05-24 18:24:29 +09001317func newPathKey(idxPath []int32) pathKey {
1318 buf := make([]byte, 4*len(idxPath))
1319 for i, x := range idxPath {
Damien Neilba1159f2018-10-17 12:53:18 -07001320 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1321 }
1322 return pathKey{string(buf)}
1323}
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001324
1325// CommentSet is a set of leading and trailing comments associated
1326// with a .proto descriptor declaration.
1327type CommentSet struct {
1328 LeadingDetached []Comments
1329 Leading Comments
1330 Trailing Comments
1331}
1332
1333// Comments is a comments string as provided by protoc.
1334type Comments string
1335
1336// String formats the comments by inserting // to the start of each line,
1337// ensuring that there is a trailing newline.
1338// An empty comment is formatted as an empty string.
1339func (c Comments) String() string {
1340 if c == "" {
1341 return ""
1342 }
1343 var b []byte
1344 for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
1345 b = append(b, "//"...)
1346 b = append(b, line...)
1347 b = append(b, "\n"...)
1348 }
1349 return string(b)
1350}