blob: 8c73c0c126405ed085ae02e3b9dbc3d224d1e5bd [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// The protoc-gen-go binary is a protoc plugin to generate a Go protocol
6// buffer package.
7package main
8
9import (
Damien Neil7779e052018-09-07 14:14:06 -070010 "bytes"
11 "compress/gzip"
12 "crypto/sha256"
13 "encoding/hex"
Damien Neil3cf6e622018-09-11 13:53:14 -070014 "flag"
Damien Neil7779e052018-09-07 14:14:06 -070015 "fmt"
Damien Neilebc699d2018-09-13 08:50:13 -070016 "math"
Damien Neilce36f8d2018-09-13 15:19:08 -070017 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070018 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070019 "strings"
Damien Neil7779e052018-09-07 14:14:06 -070020
21 "github.com/golang/protobuf/proto"
22 descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070023 "google.golang.org/proto/protogen"
Damien Neil46abb572018-09-07 12:45:37 -070024 "google.golang.org/proto/reflect/protoreflect"
Damien Neil220c2022018-08-15 11:24:18 -070025)
26
Damien Neild4127922018-09-12 11:13:49 -070027// generatedCodeVersion indicates a version of the generated code.
28// It is incremented whenever an incompatibility between the generated code and
29// proto package is introduced; the generated code references
30// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
31const generatedCodeVersion = 2
32
Damien Neil46abb572018-09-07 12:45:37 -070033const protoPackage = "github.com/golang/protobuf/proto"
34
Damien Neil220c2022018-08-15 11:24:18 -070035func main() {
Damien Neil3cf6e622018-09-11 13:53:14 -070036 var flags flag.FlagSet
37 // TODO: Decide what to do for backwards compatibility with plugins=grpc.
38 flags.String("plugins", "", "")
39 opts := &protogen.Options{
40 ParamFunc: flags.Set,
41 }
42 protogen.Run(opts, func(gen *protogen.Plugin) error {
Damien Neil220c2022018-08-15 11:24:18 -070043 for _, f := range gen.Files {
44 if !f.Generate {
45 continue
46 }
47 genFile(gen, f)
48 }
49 return nil
50 })
51}
52
Damien Neilcab8dfe2018-09-06 14:51:28 -070053type File struct {
54 *protogen.File
Damien Neil46abb572018-09-07 12:45:37 -070055 locationMap map[string][]*descpb.SourceCodeInfo_Location
56 descriptorVar string // var containing the gzipped FileDescriptorProto
Damien Neilce36f8d2018-09-13 15:19:08 -070057 allEnums []*protogen.Enum
58 allMessages []*protogen.Message
Damien Neil993c04d2018-09-14 15:41:11 -070059 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070060}
61
62func genFile(gen *protogen.Plugin, file *protogen.File) {
63 f := &File{
64 File: file,
65 locationMap: make(map[string][]*descpb.SourceCodeInfo_Location),
66 }
67 for _, loc := range file.Proto.GetSourceCodeInfo().GetLocation() {
68 key := pathKey(loc.Path)
69 f.locationMap[key] = append(f.locationMap[key], loc)
70 }
71
Damien Neil993c04d2018-09-14 15:41:11 -070072 // The different order for enums and extensions is to match the output
73 // of the previous implementation.
74 //
75 // TODO: Eventually make this consistent.
Damien Neilce36f8d2018-09-13 15:19:08 -070076 f.allEnums = append(f.allEnums, f.File.Enums...)
Damien Neil73ac8852018-09-17 15:11:24 -070077 walkMessages(f.Messages, func(message *protogen.Message) {
78 f.allMessages = append(f.allMessages, message)
79 f.allEnums = append(f.allEnums, message.Enums...)
80 f.allExtensions = append(f.allExtensions, message.Extensions...)
81 })
Damien Neil993c04d2018-09-14 15:41:11 -070082 f.allExtensions = append(f.allExtensions, f.File.Extensions...)
Damien Neilce36f8d2018-09-13 15:19:08 -070083
Damien Neil46abb572018-09-07 12:45:37 -070084 // Determine the name of the var holding the file descriptor:
85 //
86 // fileDescriptor_<hash of filename>
87 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
88 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
89
Damien Neil082ce922018-09-06 10:23:53 -070090 g := gen.NewGeneratedFile(f.GeneratedFilenamePrefix+".pb.go", f.GoImportPath)
Damien Neil220c2022018-08-15 11:24:18 -070091 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neilabc6fc12018-08-23 14:39:30 -070092 g.P("// source: ", f.Desc.Path())
Damien Neil220c2022018-08-15 11:24:18 -070093 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070094 const filePackageField = 2 // FileDescriptorProto.package
95 genComment(g, f, []int32{filePackageField})
96 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070097 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070098 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -070099
100 // These references are not necessary, since we automatically add
101 // all necessary imports before formatting the generated file.
102 //
103 // This section exists to generate output more consistent with
104 // the previous version of protoc-gen-go, to make it easier to
105 // detect unintended variations.
106 //
107 // TODO: Eventually remove this.
108 g.P("// Reference imports to suppress errors if they are not otherwise used.")
109 g.P("var _ = ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "Marshal"})
110 g.P("var _ = ", protogen.GoIdent{GoImportPath: "fmt", GoName: "Errorf"})
111 g.P("var _ = ", protogen.GoIdent{GoImportPath: "math", GoName: "Inf"})
112 g.P()
113
Damien Neild4127922018-09-12 11:13:49 -0700114 g.P("// This is a compile-time assertion to ensure that this generated file")
115 g.P("// is compatible with the proto package it is being compiled against.")
116 g.P("// A compilation error at this line likely means your copy of the")
117 g.P("// proto package needs to be updated.")
118 g.P("const _ = ", protogen.GoIdent{
119 GoImportPath: protoPackage,
120 GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion),
121 }, "// please upgrade the proto package")
122 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700123
Damien Neil73ac8852018-09-17 15:11:24 -0700124 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
125 genImport(gen, g, f, imps.Get(i))
126 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700127 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700128 genEnum(gen, g, f, enum)
129 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700130 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700131 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700132 }
Damien Neil993c04d2018-09-14 15:41:11 -0700133 for _, extension := range f.Extensions {
134 genExtension(gen, g, f, extension)
135 }
Damien Neil220c2022018-08-15 11:24:18 -0700136
Damien Neilce36f8d2018-09-13 15:19:08 -0700137 genInitFunction(gen, g, f)
Damien Neil46abb572018-09-07 12:45:37 -0700138
Damien Neil7779e052018-09-07 14:14:06 -0700139 genFileDescriptor(gen, g, f)
140}
141
Damien Neil73ac8852018-09-17 15:11:24 -0700142// walkMessages calls f on each message and all of its descendants.
143func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
144 for _, m := range messages {
145 f(m)
146 walkMessages(m.Messages, f)
147 }
148}
149
150func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700151 impFile, ok := gen.FileByName(imp.Path())
152 if !ok {
153 return
154 }
155 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700156 // Don't generate imports or aliases for types in the same Go package.
157 return
158 }
159 // Generate imports for all dependencies, even if they are not
160 // referenced, because other code and tools depend on having the
161 // full transitive closure of protocol buffer types in the binary.
162 g.Import(impFile.GoImportPath)
163 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700164 return
165 }
166 var enums []*protogen.Enum
167 enums = append(enums, impFile.Enums...)
168 walkMessages(impFile.Messages, func(message *protogen.Message) {
169 enums = append(enums, message.Enums...)
170 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
171 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
172 for _, oneof := range message.Oneofs {
173 for _, field := range oneof.Fields {
174 typ := fieldOneofType(field)
175 g.P("type ", typ.GoName, " = ", typ)
176 }
177 }
178 g.P()
179 })
180 for _, enum := range enums {
181 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
182 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
183 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
184 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
185 g.P()
186 for _, value := range enum.Values {
187 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
188 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700189 }
190}
191
Damien Neilcab8dfe2018-09-06 14:51:28 -0700192func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil7779e052018-09-07 14:14:06 -0700193 // Trim the source_code_info from the descriptor.
194 // Marshal and gzip it.
195 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
196 descProto.SourceCodeInfo = nil
197 b, err := proto.Marshal(descProto)
198 if err != nil {
199 gen.Error(err)
200 return
201 }
202 var buf bytes.Buffer
203 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
204 w.Write(b)
205 w.Close()
206 b = buf.Bytes()
207
Damien Neil46abb572018-09-07 12:45:37 -0700208 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700209 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700210 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700211 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
212 for len(b) > 0 {
213 n := 16
214 if n > len(b) {
215 n = len(b)
216 }
217
218 s := ""
219 for _, c := range b[:n] {
220 s += fmt.Sprintf("0x%02x,", c)
221 }
222 g.P(s)
223
224 b = b[n:]
225 }
226 g.P("}")
227 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700228}
Damien Neilc7d07d92018-08-22 13:46:02 -0700229
Damien Neil46abb572018-09-07 12:45:37 -0700230func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, enum *protogen.Enum) {
231 genComment(g, f, enum.Path)
232 // TODO: deprecation
233 g.P("type ", enum.GoIdent, " int32")
234 g.P("const (")
235 for _, value := range enum.Values {
236 genComment(g, f, value.Path)
237 // TODO: deprecation
238 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number())
239 }
240 g.P(")")
241 g.P()
242 nameMap := enum.GoIdent.GoName + "_name"
243 g.P("var ", nameMap, " = map[int32]string{")
244 generated := make(map[protoreflect.EnumNumber]bool)
245 for _, value := range enum.Values {
246 duplicate := ""
247 if _, present := generated[value.Desc.Number()]; present {
248 duplicate = "// Duplicate value: "
249 }
250 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
251 generated[value.Desc.Number()] = true
252 }
253 g.P("}")
254 g.P()
255 valueMap := enum.GoIdent.GoName + "_value"
256 g.P("var ", valueMap, " = map[string]int32{")
257 for _, value := range enum.Values {
258 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
259 }
260 g.P("}")
261 g.P()
262 if enum.Desc.Syntax() != protoreflect.Proto3 {
263 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
264 g.P("p := new(", enum.GoIdent, ")")
265 g.P("*p = x")
266 g.P("return p")
267 g.P("}")
268 g.P()
269 }
270 g.P("func (x ", enum.GoIdent, ") String() string {")
271 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
272 g.P("}")
273 g.P()
274
275 if enum.Desc.Syntax() != protoreflect.Proto3 {
276 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
277 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
278 g.P("if err != nil {")
279 g.P("return err")
280 g.P("}")
281 g.P("*x = ", enum.GoIdent, "(value)")
282 g.P("return nil")
283 g.P("}")
284 g.P()
285 }
286
287 var indexes []string
288 for i := 1; i < len(enum.Path); i += 2 {
289 indexes = append(indexes, strconv.Itoa(int(enum.Path[i])))
290 }
291 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
292 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
293 g.P("}")
294 g.P()
295
296 genWellKnownType(g, enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700297}
298
Damien Neil658051b2018-09-10 12:26:21 -0700299// enumRegistryName returns the name used to register an enum with the proto
300// package registry.
301//
302// Confusingly, this is <proto_package>.<go_ident>. This probably should have
303// been the full name of the proto enum type instead, but changing it at this
304// point would require thought.
305func enumRegistryName(enum *protogen.Enum) string {
306 // Find the FileDescriptor for this enum.
307 var desc protoreflect.Descriptor = enum.Desc
308 for {
309 p, ok := desc.Parent()
310 if !ok {
311 break
312 }
313 desc = p
314 }
315 fdesc := desc.(protoreflect.FileDescriptor)
316 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
317}
318
Damien Neilcab8dfe2018-09-06 14:51:28 -0700319func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700320 if message.Desc.IsMapEntry() {
321 return
322 }
323
Damien Neilcab8dfe2018-09-06 14:51:28 -0700324 genComment(g, f, message.Path)
Damien Neil658051b2018-09-10 12:26:21 -0700325 // TODO: deprecation
Damien Neilcab8dfe2018-09-06 14:51:28 -0700326 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700327 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700328 if field.OneofType != nil {
329 // It would be a bit simpler to iterate over the oneofs below,
330 // but generating the field here keeps the contents of the Go
331 // struct in the same order as the contents of the source
332 // .proto file.
333 if field == field.OneofType.Fields[0] {
334 genOneofField(gen, g, f, message, field.OneofType)
335 }
Damien Neil658051b2018-09-10 12:26:21 -0700336 continue
337 }
338 genComment(g, f, field.Path)
Damien Neil77f82fe2018-09-13 10:59:17 -0700339 goType, pointer := fieldGoType(g, field)
340 if pointer {
341 goType = "*" + goType
342 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700343 tags := []string{
344 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
345 fmt.Sprintf("json:%q", fieldJSONTag(field)),
346 }
347 if field.Desc.IsMap() {
348 key := field.MessageType.Fields[0]
349 val := field.MessageType.Fields[1]
350 tags = append(tags,
351 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
352 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
353 )
354 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700355 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
Damien Neil658051b2018-09-10 12:26:21 -0700356 }
357 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700358
359 if message.Desc.ExtensionRanges().Len() > 0 {
360 var tags []string
361 if messageOptions(gen, message).GetMessageSetWireFormat() {
362 tags = append(tags, `protobuf_messageset:"1"`)
363 }
364 tags = append(tags, `json:"-"`)
365 g.P(protogen.GoIdent{
366 GoImportPath: protoPackage,
367 GoName: "XXX_InternalExtensions",
368 }, " `", strings.Join(tags, " "), "`")
369 }
Damien Neil658051b2018-09-10 12:26:21 -0700370 // TODO XXX_InternalExtensions
371 g.P("XXX_unrecognized []byte `json:\"-\"`")
372 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700373 g.P("}")
374 g.P()
375
Damien Neila1c6abc2018-09-12 13:36:34 -0700376 // Reset
377 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
378 // String
379 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
380 GoImportPath: protoPackage,
381 GoName: "CompactTextString",
382 }, "(m) }")
383 // ProtoMessage
384 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
385 // Descriptor
386 var indexes []string
387 for i := 1; i < len(message.Path); i += 2 {
388 indexes = append(indexes, strconv.Itoa(int(message.Path[i])))
389 }
390 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
391 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
392 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700393 g.P()
394
395 // ExtensionRangeArray
396 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
397 if messageOptions(gen, message).GetMessageSetWireFormat() {
398 g.P("func (m *", message.GoIdent, ") MarshalJSON() ([]byte, error) {")
399 g.P("return ", protogen.GoIdent{
400 GoImportPath: protoPackage,
401 GoName: "MarshalMessageSetJSON",
402 }, "(&m.XXX_InternalExtensions)")
403 g.P("}")
404 g.P("func (m *", message.GoIdent, ") UnmarshalJSON(buf []byte) error {")
405 g.P("return ", protogen.GoIdent{
406 GoImportPath: protoPackage,
407 GoName: "UnmarshalMessageSetJSON",
408 }, "(buf, &m.XXX_InternalExtensions)")
409 g.P("}")
410 g.P()
411 }
412
413 protoExtRange := protogen.GoIdent{
414 GoImportPath: protoPackage,
415 GoName: "ExtensionRange",
416 }
417 extRangeVar := "extRange_" + message.GoIdent.GoName
418 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
419 for i := 0; i < extranges.Len(); i++ {
420 r := extranges.Get(i)
421 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
422 }
423 g.P("}")
424 g.P()
425 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
426 g.P("return ", extRangeVar)
427 g.P("}")
428 g.P()
429 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700430
431 // Table-driven proto support.
432 //
433 // TODO: It does not scale to keep adding another method for every
434 // operation on protos that we want to switch over to using the
435 // table-driven approach. Instead, we should only add a single method
436 // that allows getting access to the *InternalMessageInfo struct and then
437 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
438 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
439 // XXX_Unmarshal
440 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
441 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
442 g.P("}")
443 // XXX_Marshal
444 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
445 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
446 g.P("}")
447 // XXX_Merge
448 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
449 g.P(messageInfoVar, ".Merge(m, src)")
450 g.P("}")
451 // XXX_Size
452 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
453 g.P("return ", messageInfoVar, ".Size(m)")
454 g.P("}")
455 // XXX_DiscardUnknown
456 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
457 g.P(messageInfoVar, ".DiscardUnknown(m)")
458 g.P("}")
459 g.P()
460 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
461 GoImportPath: protoPackage,
462 GoName: "InternalMessageInfo",
463 })
464 g.P()
465
Damien Neilebc699d2018-09-13 08:50:13 -0700466 // Constants and vars holding the default values of fields.
467 for _, field := range message.Fields {
468 if !field.Desc.HasDefault() {
469 continue
470 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700471 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700472 def := field.Desc.Default()
473 switch field.Desc.Kind() {
474 case protoreflect.StringKind:
475 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
476 case protoreflect.BytesKind:
477 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
478 case protoreflect.EnumKind:
479 enum := field.EnumType
480 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
481 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
482 case protoreflect.FloatKind, protoreflect.DoubleKind:
483 // Floating point numbers need extra handling for -Inf/Inf/NaN.
484 f := field.Desc.Default().Float()
485 goType := "float64"
486 if field.Desc.Kind() == protoreflect.FloatKind {
487 goType = "float32"
488 }
489 // funcCall returns a call to a function in the math package,
490 // possibly converting the result to float32.
491 funcCall := func(fn, param string) string {
492 s := g.QualifiedGoIdent(protogen.GoIdent{
493 GoImportPath: "math",
494 GoName: fn,
495 }) + param
496 if goType != "float64" {
497 s = goType + "(" + s + ")"
498 }
499 return s
500 }
501 switch {
502 case math.IsInf(f, -1):
503 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
504 case math.IsInf(f, 1):
505 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
506 case math.IsNaN(f):
507 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
508 default:
509 g.P("const ", defVarName, " ", goType, " = ", f)
510 }
511 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700512 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700513 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
514 }
515 }
516 g.P()
517
Damien Neil77f82fe2018-09-13 10:59:17 -0700518 // Getters.
519 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700520 if field.OneofType != nil {
521 if field == field.OneofType.Fields[0] {
522 genOneofTypes(gen, g, f, message, field.OneofType)
523 }
524 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700525 goType, pointer := fieldGoType(g, field)
526 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil1fa78d82018-09-13 13:12:36 -0700527 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
528 if field.OneofType != nil {
529 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", message.GoIdent.GoName, "_", field.GoName, "); ok {")
530 g.P("return x.", field.GoName)
531 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700532 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700533 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
534 g.P("if m != nil {")
535 } else {
536 g.P("if m != nil && m.", field.GoName, " != nil {")
537 }
538 star := ""
539 if pointer {
540 star = "*"
541 }
542 g.P("return ", star, " m.", field.GoName)
543 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700544 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700545 g.P("return ", defaultValue)
546 g.P("}")
547 g.P()
548 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700549
Damien Neilce36f8d2018-09-13 15:19:08 -0700550 genWellKnownType(g, message.GoIdent, message.Desc)
Damien Neil1fa78d82018-09-13 13:12:36 -0700551
552 if len(message.Oneofs) > 0 {
553 genOneofFuncs(gen, g, f, message)
554 }
Damien Neil993c04d2018-09-14 15:41:11 -0700555 for _, extension := range message.Extensions {
556 genExtension(gen, g, f, extension)
557 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700558}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700559
Damien Neil77f82fe2018-09-13 10:59:17 -0700560// fieldGoType returns the Go type used for a field.
561//
562// If it returns pointer=true, the struct field is a pointer to the type.
563func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700564 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700565 switch field.Desc.Kind() {
566 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700567 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700568 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700569 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700570 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700571 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700572 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700573 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700574 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700575 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700576 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700577 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700578 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700579 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700580 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700581 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700582 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700583 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700584 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700585 goType = "[]byte"
586 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700587 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700588 if field.Desc.IsMap() {
589 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
590 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
591 return fmt.Sprintf("map[%v]%v", keyType, valType), false
592 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700593 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
594 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700595 }
596 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700597 goType = "[]" + goType
598 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700599 }
600 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700601 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700602 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700603 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700604}
605
606func fieldProtobufTag(field *protogen.Field) string {
607 var tag []string
608 // wire type
609 tag = append(tag, wireTypes[field.Desc.Kind()])
610 // field number
611 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
612 // cardinality
613 switch field.Desc.Cardinality() {
614 case protoreflect.Optional:
615 tag = append(tag, "opt")
616 case protoreflect.Required:
617 tag = append(tag, "req")
618 case protoreflect.Repeated:
619 tag = append(tag, "rep")
620 }
Damien Neil658051b2018-09-10 12:26:21 -0700621 // TODO: packed
622 // name
623 name := string(field.Desc.Name())
624 if field.Desc.Kind() == protoreflect.GroupKind {
625 // The name of the FieldDescriptor for a group field is
626 // lowercased. To find the original capitalization, we
627 // look in the field's MessageType.
628 name = string(field.MessageType.Desc.Name())
629 }
630 tag = append(tag, "name="+name)
631 // JSON name
632 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
633 tag = append(tag, "json="+jsonName)
634 }
635 // proto3
636 if field.Desc.Syntax() == protoreflect.Proto3 {
637 tag = append(tag, "proto3")
638 }
639 // enum
640 if field.Desc.Kind() == protoreflect.EnumKind {
641 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
642 }
643 // oneof
644 if field.Desc.OneofType() != nil {
645 tag = append(tag, "oneof")
646 }
Damien Neilebc699d2018-09-13 08:50:13 -0700647 // default value
648 // This must appear last in the tag, since commas in strings aren't escaped.
649 if field.Desc.HasDefault() {
650 var def string
651 switch field.Desc.Kind() {
652 case protoreflect.BoolKind:
653 if field.Desc.Default().Bool() {
654 def = "1"
655 } else {
656 def = "0"
657 }
658 case protoreflect.BytesKind:
659 def = string(field.Desc.Default().Bytes())
660 case protoreflect.FloatKind, protoreflect.DoubleKind:
661 f := field.Desc.Default().Float()
662 switch {
663 case math.IsInf(f, -1):
664 def = "-inf"
665 case math.IsInf(f, 1):
666 def = "inf"
667 case math.IsNaN(f):
668 def = "nan"
669 default:
670 def = fmt.Sprint(f)
671 }
672 default:
673 def = fmt.Sprint(field.Desc.Default().Interface())
674 }
675 tag = append(tag, "def="+def)
676 }
Damien Neil658051b2018-09-10 12:26:21 -0700677 return strings.Join(tag, ",")
678}
679
Damien Neil77f82fe2018-09-13 10:59:17 -0700680func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
681 if field.Desc.Cardinality() == protoreflect.Repeated {
682 return "nil"
683 }
684 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700685 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700686 if field.Desc.Kind() == protoreflect.BytesKind {
687 return "append([]byte(nil), " + defVarName + "...)"
688 }
689 return defVarName
690 }
691 switch field.Desc.Kind() {
692 case protoreflect.BoolKind:
693 return "false"
694 case protoreflect.StringKind:
695 return `""`
696 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
697 return "nil"
698 case protoreflect.EnumKind:
699 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
700 default:
701 return "0"
702 }
703}
704
Damien Neil658051b2018-09-10 12:26:21 -0700705var wireTypes = map[protoreflect.Kind]string{
706 protoreflect.BoolKind: "varint",
707 protoreflect.EnumKind: "varint",
708 protoreflect.Int32Kind: "varint",
709 protoreflect.Sint32Kind: "zigzag32",
710 protoreflect.Uint32Kind: "varint",
711 protoreflect.Int64Kind: "varint",
712 protoreflect.Sint64Kind: "zigzag64",
713 protoreflect.Uint64Kind: "varint",
714 protoreflect.Sfixed32Kind: "fixed32",
715 protoreflect.Fixed32Kind: "fixed32",
716 protoreflect.FloatKind: "fixed32",
717 protoreflect.Sfixed64Kind: "fixed64",
718 protoreflect.Fixed64Kind: "fixed64",
719 protoreflect.DoubleKind: "fixed64",
720 protoreflect.StringKind: "bytes",
721 protoreflect.BytesKind: "bytes",
722 protoreflect.MessageKind: "bytes",
723 protoreflect.GroupKind: "group",
724}
725
726func fieldJSONTag(field *protogen.Field) string {
727 return string(field.Desc.Name()) + ",omitempty"
728}
729
Damien Neil993c04d2018-09-14 15:41:11 -0700730func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, extension *protogen.Extension) {
731 g.P("var ", extensionVar(f, extension), " = &", protogen.GoIdent{
732 GoImportPath: protoPackage,
733 GoName: "ExtensionDesc",
734 }, "{")
735 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
736 goType, pointer := fieldGoType(g, extension)
737 if pointer {
738 goType = "*" + goType
739 }
740 g.P("ExtensionType: (", goType, ")(nil),")
741 g.P("Field: ", extension.Desc.Number(), ",")
742 g.P("Name: ", strconv.Quote(string(extension.Desc.FullName())), ",")
743 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
744 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
745 g.P("}")
746 g.P()
747}
748
749// extensionVar returns the var holding the ExtensionDesc for an extension.
750func extensionVar(f *File, extension *protogen.Extension) protogen.GoIdent {
751 name := "E_"
752 if extension.ParentMessage != nil {
753 name += extension.ParentMessage.GoIdent.GoName + "_"
754 }
755 name += extension.GoName
756 return protogen.GoIdent{
757 GoImportPath: f.GoImportPath,
758 GoName: name,
759 }
760}
761
Damien Neilce36f8d2018-09-13 15:19:08 -0700762// genInitFunction generates an init function that registers the types in the
763// generated file with the proto package.
764func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil993c04d2018-09-14 15:41:11 -0700765 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700766 return
767 }
768
769 g.P("func init() {")
770 for _, message := range f.allMessages {
771 if message.Desc.IsMapEntry() {
772 continue
773 }
774
775 name := message.GoIdent.GoName
776 g.P(protogen.GoIdent{
777 GoImportPath: protoPackage,
778 GoName: "RegisterType",
779 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
780
781 // Types of map fields, sorted by the name of the field message type.
782 var mapFields []*protogen.Field
783 for _, field := range message.Fields {
784 if field.Desc.IsMap() {
785 mapFields = append(mapFields, field)
786 }
787 }
788 sort.Slice(mapFields, func(i, j int) bool {
789 ni := mapFields[i].MessageType.Desc.FullName()
790 nj := mapFields[j].MessageType.Desc.FullName()
791 return ni < nj
792 })
793 for _, field := range mapFields {
794 typeName := string(field.MessageType.Desc.FullName())
795 goType, _ := fieldGoType(g, field)
796 g.P(protogen.GoIdent{
797 GoImportPath: protoPackage,
798 GoName: "RegisterMapType",
799 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
800 }
801 }
802 for _, enum := range f.allEnums {
803 name := enum.GoIdent.GoName
804 g.P(protogen.GoIdent{
805 GoImportPath: protoPackage,
806 GoName: "RegisterEnum",
807 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
808 }
Damien Neil993c04d2018-09-14 15:41:11 -0700809 for _, extension := range f.allExtensions {
810 g.P(protogen.GoIdent{
811 GoImportPath: protoPackage,
812 GoName: "RegisterExtension",
813 }, "(", extensionVar(f, extension), ")")
814 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700815 g.P("}")
816 g.P()
817}
818
Damien Neil1fa78d82018-09-13 13:12:36 -0700819func genComment(g *protogen.GeneratedFile, f *File, path []int32) (hasComment bool) {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700820 for _, loc := range f.locationMap[pathKey(path)] {
821 if loc.LeadingComments == nil {
822 continue
823 }
824 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
Damien Neil1fa78d82018-09-13 13:12:36 -0700825 hasComment = true
Damien Neilcab8dfe2018-09-06 14:51:28 -0700826 g.P("//", line)
827 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700828 break
Damien Neilcab8dfe2018-09-06 14:51:28 -0700829 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700830 return hasComment
Damien Neilcab8dfe2018-09-06 14:51:28 -0700831}
832
833// pathKey converts a location path to a string suitable for use as a map key.
834func pathKey(path []int32) string {
835 var buf []byte
836 for i, x := range path {
837 if i != 0 {
838 buf = append(buf, ',')
839 }
840 buf = strconv.AppendInt(buf, int64(x), 10)
841 }
842 return string(buf)
843}
Damien Neil46abb572018-09-07 12:45:37 -0700844
845func genWellKnownType(g *protogen.GeneratedFile, ident protogen.GoIdent, desc protoreflect.Descriptor) {
846 if wellKnownTypes[desc.FullName()] {
847 g.P("func (", ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
848 g.P()
849 }
850}
851
852// Names of messages and enums for which we will generate XXX_WellKnownType methods.
853var wellKnownTypes = map[protoreflect.FullName]bool{
854 "google.protobuf.NullValue": true,
855}