blob: 28745ae6715b67ccb14e9e386c1d4daa530146a1 [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"
Joe Tsai01ab2962018-09-21 17:44:00 -070023 "github.com/golang/protobuf/v2/protogen"
24 "github.com/golang/protobuf/v2/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 Neil55fe1c02018-09-17 15:11:24 -070092 if f.Proto.GetOptions().GetDeprecated() {
93 g.P("// ", f.Desc.Path(), " is a deprecated file.")
94 } else {
95 g.P("// source: ", f.Desc.Path())
96 }
Damien Neil220c2022018-08-15 11:24:18 -070097 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070098 const filePackageField = 2 // FileDescriptorProto.package
99 genComment(g, f, []int32{filePackageField})
100 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700101 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700102 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700103
104 // These references are not necessary, since we automatically add
105 // all necessary imports before formatting the generated file.
106 //
107 // This section exists to generate output more consistent with
108 // the previous version of protoc-gen-go, to make it easier to
109 // detect unintended variations.
110 //
111 // TODO: Eventually remove this.
112 g.P("// Reference imports to suppress errors if they are not otherwise used.")
113 g.P("var _ = ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "Marshal"})
114 g.P("var _ = ", protogen.GoIdent{GoImportPath: "fmt", GoName: "Errorf"})
115 g.P("var _ = ", protogen.GoIdent{GoImportPath: "math", GoName: "Inf"})
116 g.P()
117
Damien Neild4127922018-09-12 11:13:49 -0700118 g.P("// This is a compile-time assertion to ensure that this generated file")
119 g.P("// is compatible with the proto package it is being compiled against.")
120 g.P("// A compilation error at this line likely means your copy of the")
121 g.P("// proto package needs to be updated.")
122 g.P("const _ = ", protogen.GoIdent{
123 GoImportPath: protoPackage,
124 GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion),
125 }, "// please upgrade the proto package")
126 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700127
Damien Neil73ac8852018-09-17 15:11:24 -0700128 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
129 genImport(gen, g, f, imps.Get(i))
130 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700131 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700132 genEnum(gen, g, f, enum)
133 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700134 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700135 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700136 }
Damien Neil993c04d2018-09-14 15:41:11 -0700137 for _, extension := range f.Extensions {
138 genExtension(gen, g, f, extension)
139 }
Damien Neil220c2022018-08-15 11:24:18 -0700140
Damien Neilce36f8d2018-09-13 15:19:08 -0700141 genInitFunction(gen, g, f)
Damien Neil46abb572018-09-07 12:45:37 -0700142
Damien Neil7779e052018-09-07 14:14:06 -0700143 genFileDescriptor(gen, g, f)
144}
145
Damien Neil73ac8852018-09-17 15:11:24 -0700146// walkMessages calls f on each message and all of its descendants.
147func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
148 for _, m := range messages {
149 f(m)
150 walkMessages(m.Messages, f)
151 }
152}
153
154func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700155 impFile, ok := gen.FileByName(imp.Path())
156 if !ok {
157 return
158 }
159 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700160 // Don't generate imports or aliases for types in the same Go package.
161 return
162 }
163 // Generate imports for all dependencies, even if they are not
164 // referenced, because other code and tools depend on having the
165 // full transitive closure of protocol buffer types in the binary.
166 g.Import(impFile.GoImportPath)
167 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700168 return
169 }
170 var enums []*protogen.Enum
171 enums = append(enums, impFile.Enums...)
172 walkMessages(impFile.Messages, func(message *protogen.Message) {
173 enums = append(enums, message.Enums...)
174 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
175 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
176 for _, oneof := range message.Oneofs {
177 for _, field := range oneof.Fields {
178 typ := fieldOneofType(field)
179 g.P("type ", typ.GoName, " = ", typ)
180 }
181 }
182 g.P()
183 })
184 for _, enum := range enums {
185 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
186 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
187 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
188 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
189 g.P()
190 for _, value := range enum.Values {
191 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
192 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700193 }
194}
195
Damien Neilcab8dfe2018-09-06 14:51:28 -0700196func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil7779e052018-09-07 14:14:06 -0700197 // Trim the source_code_info from the descriptor.
198 // Marshal and gzip it.
199 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
200 descProto.SourceCodeInfo = nil
201 b, err := proto.Marshal(descProto)
202 if err != nil {
203 gen.Error(err)
204 return
205 }
206 var buf bytes.Buffer
207 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
208 w.Write(b)
209 w.Close()
210 b = buf.Bytes()
211
Damien Neil46abb572018-09-07 12:45:37 -0700212 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700213 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700214 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700215 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
216 for len(b) > 0 {
217 n := 16
218 if n > len(b) {
219 n = len(b)
220 }
221
222 s := ""
223 for _, c := range b[:n] {
224 s += fmt.Sprintf("0x%02x,", c)
225 }
226 g.P(s)
227
228 b = b[n:]
229 }
230 g.P("}")
231 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700232}
Damien Neilc7d07d92018-08-22 13:46:02 -0700233
Damien Neil46abb572018-09-07 12:45:37 -0700234func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, enum *protogen.Enum) {
235 genComment(g, f, enum.Path)
Damien Neil55fe1c02018-09-17 15:11:24 -0700236 g.P("type ", enum.GoIdent, " int32",
237 deprecationComment(enumOptions(gen, enum).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700238 g.P("const (")
239 for _, value := range enum.Values {
240 genComment(g, f, value.Path)
Damien Neil55fe1c02018-09-17 15:11:24 -0700241 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
242 deprecationComment(enumValueOptions(gen, value).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700243 }
244 g.P(")")
245 g.P()
246 nameMap := enum.GoIdent.GoName + "_name"
247 g.P("var ", nameMap, " = map[int32]string{")
248 generated := make(map[protoreflect.EnumNumber]bool)
249 for _, value := range enum.Values {
250 duplicate := ""
251 if _, present := generated[value.Desc.Number()]; present {
252 duplicate = "// Duplicate value: "
253 }
254 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
255 generated[value.Desc.Number()] = true
256 }
257 g.P("}")
258 g.P()
259 valueMap := enum.GoIdent.GoName + "_value"
260 g.P("var ", valueMap, " = map[string]int32{")
261 for _, value := range enum.Values {
262 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
263 }
264 g.P("}")
265 g.P()
266 if enum.Desc.Syntax() != protoreflect.Proto3 {
267 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
268 g.P("p := new(", enum.GoIdent, ")")
269 g.P("*p = x")
270 g.P("return p")
271 g.P("}")
272 g.P()
273 }
274 g.P("func (x ", enum.GoIdent, ") String() string {")
275 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
276 g.P("}")
277 g.P()
278
279 if enum.Desc.Syntax() != protoreflect.Proto3 {
280 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
281 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
282 g.P("if err != nil {")
283 g.P("return err")
284 g.P("}")
285 g.P("*x = ", enum.GoIdent, "(value)")
286 g.P("return nil")
287 g.P("}")
288 g.P()
289 }
290
291 var indexes []string
292 for i := 1; i < len(enum.Path); i += 2 {
293 indexes = append(indexes, strconv.Itoa(int(enum.Path[i])))
294 }
295 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
296 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
297 g.P("}")
298 g.P()
299
300 genWellKnownType(g, enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700301}
302
Damien Neil658051b2018-09-10 12:26:21 -0700303// enumRegistryName returns the name used to register an enum with the proto
304// package registry.
305//
306// Confusingly, this is <proto_package>.<go_ident>. This probably should have
307// been the full name of the proto enum type instead, but changing it at this
308// point would require thought.
309func enumRegistryName(enum *protogen.Enum) string {
310 // Find the FileDescriptor for this enum.
311 var desc protoreflect.Descriptor = enum.Desc
312 for {
313 p, ok := desc.Parent()
314 if !ok {
315 break
316 }
317 desc = p
318 }
319 fdesc := desc.(protoreflect.FileDescriptor)
320 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
321}
322
Damien Neilcab8dfe2018-09-06 14:51:28 -0700323func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700324 if message.Desc.IsMapEntry() {
325 return
326 }
327
Damien Neil55fe1c02018-09-17 15:11:24 -0700328 hasComment := genComment(g, f, message.Path)
329 if messageOptions(gen, message).GetDeprecated() {
330 if hasComment {
331 g.P("//")
332 }
333 g.P(deprecationComment(true))
334 }
Damien Neilcab8dfe2018-09-06 14:51:28 -0700335 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700336 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700337 if field.OneofType != nil {
338 // It would be a bit simpler to iterate over the oneofs below,
339 // but generating the field here keeps the contents of the Go
340 // struct in the same order as the contents of the source
341 // .proto file.
342 if field == field.OneofType.Fields[0] {
343 genOneofField(gen, g, f, message, field.OneofType)
344 }
Damien Neil658051b2018-09-10 12:26:21 -0700345 continue
346 }
347 genComment(g, f, field.Path)
Damien Neil77f82fe2018-09-13 10:59:17 -0700348 goType, pointer := fieldGoType(g, field)
349 if pointer {
350 goType = "*" + goType
351 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700352 tags := []string{
353 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
354 fmt.Sprintf("json:%q", fieldJSONTag(field)),
355 }
356 if field.Desc.IsMap() {
357 key := field.MessageType.Fields[0]
358 val := field.MessageType.Fields[1]
359 tags = append(tags,
360 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
361 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
362 )
363 }
Damien Neil55fe1c02018-09-17 15:11:24 -0700364 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
365 deprecationComment(fieldOptions(gen, field).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700366 }
367 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700368
369 if message.Desc.ExtensionRanges().Len() > 0 {
370 var tags []string
371 if messageOptions(gen, message).GetMessageSetWireFormat() {
372 tags = append(tags, `protobuf_messageset:"1"`)
373 }
374 tags = append(tags, `json:"-"`)
375 g.P(protogen.GoIdent{
376 GoImportPath: protoPackage,
377 GoName: "XXX_InternalExtensions",
378 }, " `", strings.Join(tags, " "), "`")
379 }
Damien Neil658051b2018-09-10 12:26:21 -0700380 // TODO XXX_InternalExtensions
381 g.P("XXX_unrecognized []byte `json:\"-\"`")
382 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700383 g.P("}")
384 g.P()
385
Damien Neila1c6abc2018-09-12 13:36:34 -0700386 // Reset
387 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
388 // String
389 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
390 GoImportPath: protoPackage,
391 GoName: "CompactTextString",
392 }, "(m) }")
393 // ProtoMessage
394 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
395 // Descriptor
396 var indexes []string
397 for i := 1; i < len(message.Path); i += 2 {
398 indexes = append(indexes, strconv.Itoa(int(message.Path[i])))
399 }
400 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
401 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
402 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700403 g.P()
404
405 // ExtensionRangeArray
406 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
407 if messageOptions(gen, message).GetMessageSetWireFormat() {
408 g.P("func (m *", message.GoIdent, ") MarshalJSON() ([]byte, error) {")
409 g.P("return ", protogen.GoIdent{
410 GoImportPath: protoPackage,
411 GoName: "MarshalMessageSetJSON",
412 }, "(&m.XXX_InternalExtensions)")
413 g.P("}")
414 g.P("func (m *", message.GoIdent, ") UnmarshalJSON(buf []byte) error {")
415 g.P("return ", protogen.GoIdent{
416 GoImportPath: protoPackage,
417 GoName: "UnmarshalMessageSetJSON",
418 }, "(buf, &m.XXX_InternalExtensions)")
419 g.P("}")
420 g.P()
421 }
422
423 protoExtRange := protogen.GoIdent{
424 GoImportPath: protoPackage,
425 GoName: "ExtensionRange",
426 }
427 extRangeVar := "extRange_" + message.GoIdent.GoName
428 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
429 for i := 0; i < extranges.Len(); i++ {
430 r := extranges.Get(i)
431 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
432 }
433 g.P("}")
434 g.P()
435 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
436 g.P("return ", extRangeVar)
437 g.P("}")
438 g.P()
439 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700440
441 // Table-driven proto support.
442 //
443 // TODO: It does not scale to keep adding another method for every
444 // operation on protos that we want to switch over to using the
445 // table-driven approach. Instead, we should only add a single method
446 // that allows getting access to the *InternalMessageInfo struct and then
447 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
448 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
449 // XXX_Unmarshal
450 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
451 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
452 g.P("}")
453 // XXX_Marshal
454 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
455 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
456 g.P("}")
457 // XXX_Merge
458 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
459 g.P(messageInfoVar, ".Merge(m, src)")
460 g.P("}")
461 // XXX_Size
462 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
463 g.P("return ", messageInfoVar, ".Size(m)")
464 g.P("}")
465 // XXX_DiscardUnknown
466 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
467 g.P(messageInfoVar, ".DiscardUnknown(m)")
468 g.P("}")
469 g.P()
470 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
471 GoImportPath: protoPackage,
472 GoName: "InternalMessageInfo",
473 })
474 g.P()
475
Damien Neilebc699d2018-09-13 08:50:13 -0700476 // Constants and vars holding the default values of fields.
477 for _, field := range message.Fields {
478 if !field.Desc.HasDefault() {
479 continue
480 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700481 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700482 def := field.Desc.Default()
483 switch field.Desc.Kind() {
484 case protoreflect.StringKind:
485 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
486 case protoreflect.BytesKind:
487 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
488 case protoreflect.EnumKind:
489 enum := field.EnumType
490 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
491 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
492 case protoreflect.FloatKind, protoreflect.DoubleKind:
493 // Floating point numbers need extra handling for -Inf/Inf/NaN.
494 f := field.Desc.Default().Float()
495 goType := "float64"
496 if field.Desc.Kind() == protoreflect.FloatKind {
497 goType = "float32"
498 }
499 // funcCall returns a call to a function in the math package,
500 // possibly converting the result to float32.
501 funcCall := func(fn, param string) string {
502 s := g.QualifiedGoIdent(protogen.GoIdent{
503 GoImportPath: "math",
504 GoName: fn,
505 }) + param
506 if goType != "float64" {
507 s = goType + "(" + s + ")"
508 }
509 return s
510 }
511 switch {
512 case math.IsInf(f, -1):
513 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
514 case math.IsInf(f, 1):
515 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
516 case math.IsNaN(f):
517 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
518 default:
519 g.P("const ", defVarName, " ", goType, " = ", f)
520 }
521 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700522 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700523 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
524 }
525 }
526 g.P()
527
Damien Neil77f82fe2018-09-13 10:59:17 -0700528 // Getters.
529 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700530 if field.OneofType != nil {
531 if field == field.OneofType.Fields[0] {
532 genOneofTypes(gen, g, f, message, field.OneofType)
533 }
534 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700535 goType, pointer := fieldGoType(g, field)
536 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil55fe1c02018-09-17 15:11:24 -0700537 if fieldOptions(gen, field).GetDeprecated() {
538 g.P(deprecationComment(true))
539 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700540 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
541 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700542 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700543 g.P("return x.", field.GoName)
544 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700545 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700546 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
547 g.P("if m != nil {")
548 } else {
549 g.P("if m != nil && m.", field.GoName, " != nil {")
550 }
551 star := ""
552 if pointer {
553 star = "*"
554 }
555 g.P("return ", star, " m.", field.GoName)
556 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700557 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700558 g.P("return ", defaultValue)
559 g.P("}")
560 g.P()
561 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700562
Damien Neilce36f8d2018-09-13 15:19:08 -0700563 genWellKnownType(g, message.GoIdent, message.Desc)
Damien Neil1fa78d82018-09-13 13:12:36 -0700564
565 if len(message.Oneofs) > 0 {
566 genOneofFuncs(gen, g, f, message)
567 }
Damien Neil993c04d2018-09-14 15:41:11 -0700568 for _, extension := range message.Extensions {
569 genExtension(gen, g, f, extension)
570 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700571}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700572
Damien Neil77f82fe2018-09-13 10:59:17 -0700573// fieldGoType returns the Go type used for a field.
574//
575// If it returns pointer=true, the struct field is a pointer to the type.
576func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700577 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700578 switch field.Desc.Kind() {
579 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700580 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700581 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700582 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700583 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700584 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700585 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700586 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700587 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700588 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700589 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700590 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700591 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700592 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700593 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700594 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700595 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700596 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700597 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700598 goType = "[]byte"
599 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700600 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700601 if field.Desc.IsMap() {
602 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
603 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
604 return fmt.Sprintf("map[%v]%v", keyType, valType), false
605 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700606 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
607 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700608 }
609 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700610 goType = "[]" + goType
611 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700612 }
613 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700615 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700617}
618
619func fieldProtobufTag(field *protogen.Field) string {
620 var tag []string
621 // wire type
622 tag = append(tag, wireTypes[field.Desc.Kind()])
623 // field number
624 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
625 // cardinality
626 switch field.Desc.Cardinality() {
627 case protoreflect.Optional:
628 tag = append(tag, "opt")
629 case protoreflect.Required:
630 tag = append(tag, "req")
631 case protoreflect.Repeated:
632 tag = append(tag, "rep")
633 }
Damien Neild4803f52018-09-19 11:43:35 -0700634 if field.Desc.IsPacked() {
635 tag = append(tag, "packed")
636 }
Damien Neil658051b2018-09-10 12:26:21 -0700637 // TODO: packed
638 // name
639 name := string(field.Desc.Name())
640 if field.Desc.Kind() == protoreflect.GroupKind {
641 // The name of the FieldDescriptor for a group field is
642 // lowercased. To find the original capitalization, we
643 // look in the field's MessageType.
644 name = string(field.MessageType.Desc.Name())
645 }
646 tag = append(tag, "name="+name)
647 // JSON name
648 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
649 tag = append(tag, "json="+jsonName)
650 }
651 // proto3
652 if field.Desc.Syntax() == protoreflect.Proto3 {
653 tag = append(tag, "proto3")
654 }
655 // enum
656 if field.Desc.Kind() == protoreflect.EnumKind {
657 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
658 }
659 // oneof
660 if field.Desc.OneofType() != nil {
661 tag = append(tag, "oneof")
662 }
Damien Neilebc699d2018-09-13 08:50:13 -0700663 // default value
664 // This must appear last in the tag, since commas in strings aren't escaped.
665 if field.Desc.HasDefault() {
666 var def string
667 switch field.Desc.Kind() {
668 case protoreflect.BoolKind:
669 if field.Desc.Default().Bool() {
670 def = "1"
671 } else {
672 def = "0"
673 }
674 case protoreflect.BytesKind:
675 def = string(field.Desc.Default().Bytes())
676 case protoreflect.FloatKind, protoreflect.DoubleKind:
677 f := field.Desc.Default().Float()
678 switch {
679 case math.IsInf(f, -1):
680 def = "-inf"
681 case math.IsInf(f, 1):
682 def = "inf"
683 case math.IsNaN(f):
684 def = "nan"
685 default:
686 def = fmt.Sprint(f)
687 }
688 default:
689 def = fmt.Sprint(field.Desc.Default().Interface())
690 }
691 tag = append(tag, "def="+def)
692 }
Damien Neil658051b2018-09-10 12:26:21 -0700693 return strings.Join(tag, ",")
694}
695
Damien Neil77f82fe2018-09-13 10:59:17 -0700696func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
697 if field.Desc.Cardinality() == protoreflect.Repeated {
698 return "nil"
699 }
700 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700701 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700702 if field.Desc.Kind() == protoreflect.BytesKind {
703 return "append([]byte(nil), " + defVarName + "...)"
704 }
705 return defVarName
706 }
707 switch field.Desc.Kind() {
708 case protoreflect.BoolKind:
709 return "false"
710 case protoreflect.StringKind:
711 return `""`
712 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
713 return "nil"
714 case protoreflect.EnumKind:
715 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
716 default:
717 return "0"
718 }
719}
720
Damien Neil658051b2018-09-10 12:26:21 -0700721var wireTypes = map[protoreflect.Kind]string{
722 protoreflect.BoolKind: "varint",
723 protoreflect.EnumKind: "varint",
724 protoreflect.Int32Kind: "varint",
725 protoreflect.Sint32Kind: "zigzag32",
726 protoreflect.Uint32Kind: "varint",
727 protoreflect.Int64Kind: "varint",
728 protoreflect.Sint64Kind: "zigzag64",
729 protoreflect.Uint64Kind: "varint",
730 protoreflect.Sfixed32Kind: "fixed32",
731 protoreflect.Fixed32Kind: "fixed32",
732 protoreflect.FloatKind: "fixed32",
733 protoreflect.Sfixed64Kind: "fixed64",
734 protoreflect.Fixed64Kind: "fixed64",
735 protoreflect.DoubleKind: "fixed64",
736 protoreflect.StringKind: "bytes",
737 protoreflect.BytesKind: "bytes",
738 protoreflect.MessageKind: "bytes",
739 protoreflect.GroupKind: "group",
740}
741
742func fieldJSONTag(field *protogen.Field) string {
743 return string(field.Desc.Name()) + ",omitempty"
744}
745
Damien Neil993c04d2018-09-14 15:41:11 -0700746func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, extension *protogen.Extension) {
747 g.P("var ", extensionVar(f, extension), " = &", protogen.GoIdent{
748 GoImportPath: protoPackage,
749 GoName: "ExtensionDesc",
750 }, "{")
751 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
752 goType, pointer := fieldGoType(g, extension)
753 if pointer {
754 goType = "*" + goType
755 }
756 g.P("ExtensionType: (", goType, ")(nil),")
757 g.P("Field: ", extension.Desc.Number(), ",")
758 g.P("Name: ", strconv.Quote(string(extension.Desc.FullName())), ",")
759 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
760 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
761 g.P("}")
762 g.P()
763}
764
765// extensionVar returns the var holding the ExtensionDesc for an extension.
766func extensionVar(f *File, extension *protogen.Extension) protogen.GoIdent {
767 name := "E_"
768 if extension.ParentMessage != nil {
769 name += extension.ParentMessage.GoIdent.GoName + "_"
770 }
771 name += extension.GoName
772 return protogen.GoIdent{
773 GoImportPath: f.GoImportPath,
774 GoName: name,
775 }
776}
777
Damien Neilce36f8d2018-09-13 15:19:08 -0700778// genInitFunction generates an init function that registers the types in the
779// generated file with the proto package.
780func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil993c04d2018-09-14 15:41:11 -0700781 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700782 return
783 }
784
785 g.P("func init() {")
786 for _, message := range f.allMessages {
787 if message.Desc.IsMapEntry() {
788 continue
789 }
790
791 name := message.GoIdent.GoName
792 g.P(protogen.GoIdent{
793 GoImportPath: protoPackage,
794 GoName: "RegisterType",
795 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
796
797 // Types of map fields, sorted by the name of the field message type.
798 var mapFields []*protogen.Field
799 for _, field := range message.Fields {
800 if field.Desc.IsMap() {
801 mapFields = append(mapFields, field)
802 }
803 }
804 sort.Slice(mapFields, func(i, j int) bool {
805 ni := mapFields[i].MessageType.Desc.FullName()
806 nj := mapFields[j].MessageType.Desc.FullName()
807 return ni < nj
808 })
809 for _, field := range mapFields {
810 typeName := string(field.MessageType.Desc.FullName())
811 goType, _ := fieldGoType(g, field)
812 g.P(protogen.GoIdent{
813 GoImportPath: protoPackage,
814 GoName: "RegisterMapType",
815 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
816 }
817 }
818 for _, enum := range f.allEnums {
819 name := enum.GoIdent.GoName
820 g.P(protogen.GoIdent{
821 GoImportPath: protoPackage,
822 GoName: "RegisterEnum",
823 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
824 }
Damien Neil993c04d2018-09-14 15:41:11 -0700825 for _, extension := range f.allExtensions {
826 g.P(protogen.GoIdent{
827 GoImportPath: protoPackage,
828 GoName: "RegisterExtension",
829 }, "(", extensionVar(f, extension), ")")
830 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700831 g.P("}")
832 g.P()
833}
834
Damien Neil1fa78d82018-09-13 13:12:36 -0700835func genComment(g *protogen.GeneratedFile, f *File, path []int32) (hasComment bool) {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700836 for _, loc := range f.locationMap[pathKey(path)] {
837 if loc.LeadingComments == nil {
838 continue
839 }
840 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
Damien Neil1fa78d82018-09-13 13:12:36 -0700841 hasComment = true
Damien Neilcab8dfe2018-09-06 14:51:28 -0700842 g.P("//", line)
843 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700844 break
Damien Neilcab8dfe2018-09-06 14:51:28 -0700845 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700846 return hasComment
Damien Neilcab8dfe2018-09-06 14:51:28 -0700847}
848
Damien Neil55fe1c02018-09-17 15:11:24 -0700849// deprecationComment returns a standard deprecation comment if deprecated is true.
850func deprecationComment(deprecated bool) string {
851 if !deprecated {
852 return ""
853 }
854 return "// Deprecated: Do not use."
855}
856
Damien Neilcab8dfe2018-09-06 14:51:28 -0700857// pathKey converts a location path to a string suitable for use as a map key.
858func pathKey(path []int32) string {
859 var buf []byte
860 for i, x := range path {
861 if i != 0 {
862 buf = append(buf, ',')
863 }
864 buf = strconv.AppendInt(buf, int64(x), 10)
865 }
866 return string(buf)
867}
Damien Neil46abb572018-09-07 12:45:37 -0700868
869func genWellKnownType(g *protogen.GeneratedFile, ident protogen.GoIdent, desc protoreflect.Descriptor) {
870 if wellKnownTypes[desc.FullName()] {
871 g.P("func (", ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
872 g.P()
873 }
874}
875
876// Names of messages and enums for which we will generate XXX_WellKnownType methods.
877var wellKnownTypes = map[protoreflect.FullName]bool{
878 "google.protobuf.NullValue": true,
879}