blob: b477fe74ca10bda5295fb7f34ca1f78b43be74e0 [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) {
151 if !imp.IsPublic {
152 return
153 }
154 impFile, ok := gen.FileByName(imp.Path())
155 if !ok {
156 return
157 }
158 if impFile.GoImportPath == f.GoImportPath {
159 // Don't generate aliases for types in the same Go package.
160 return
161 }
162 var enums []*protogen.Enum
163 enums = append(enums, impFile.Enums...)
164 walkMessages(impFile.Messages, func(message *protogen.Message) {
165 enums = append(enums, message.Enums...)
166 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
167 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
168 for _, oneof := range message.Oneofs {
169 for _, field := range oneof.Fields {
170 typ := fieldOneofType(field)
171 g.P("type ", typ.GoName, " = ", typ)
172 }
173 }
174 g.P()
175 })
176 for _, enum := range enums {
177 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
178 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
179 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
180 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
181 g.P()
182 for _, value := range enum.Values {
183 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
184 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700185 }
186}
187
Damien Neilcab8dfe2018-09-06 14:51:28 -0700188func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil7779e052018-09-07 14:14:06 -0700189 // Trim the source_code_info from the descriptor.
190 // Marshal and gzip it.
191 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
192 descProto.SourceCodeInfo = nil
193 b, err := proto.Marshal(descProto)
194 if err != nil {
195 gen.Error(err)
196 return
197 }
198 var buf bytes.Buffer
199 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
200 w.Write(b)
201 w.Close()
202 b = buf.Bytes()
203
Damien Neil46abb572018-09-07 12:45:37 -0700204 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700205 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700206 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700207 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
208 for len(b) > 0 {
209 n := 16
210 if n > len(b) {
211 n = len(b)
212 }
213
214 s := ""
215 for _, c := range b[:n] {
216 s += fmt.Sprintf("0x%02x,", c)
217 }
218 g.P(s)
219
220 b = b[n:]
221 }
222 g.P("}")
223 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700224}
Damien Neilc7d07d92018-08-22 13:46:02 -0700225
Damien Neil46abb572018-09-07 12:45:37 -0700226func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, enum *protogen.Enum) {
227 genComment(g, f, enum.Path)
228 // TODO: deprecation
229 g.P("type ", enum.GoIdent, " int32")
230 g.P("const (")
231 for _, value := range enum.Values {
232 genComment(g, f, value.Path)
233 // TODO: deprecation
234 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number())
235 }
236 g.P(")")
237 g.P()
238 nameMap := enum.GoIdent.GoName + "_name"
239 g.P("var ", nameMap, " = map[int32]string{")
240 generated := make(map[protoreflect.EnumNumber]bool)
241 for _, value := range enum.Values {
242 duplicate := ""
243 if _, present := generated[value.Desc.Number()]; present {
244 duplicate = "// Duplicate value: "
245 }
246 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
247 generated[value.Desc.Number()] = true
248 }
249 g.P("}")
250 g.P()
251 valueMap := enum.GoIdent.GoName + "_value"
252 g.P("var ", valueMap, " = map[string]int32{")
253 for _, value := range enum.Values {
254 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
255 }
256 g.P("}")
257 g.P()
258 if enum.Desc.Syntax() != protoreflect.Proto3 {
259 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
260 g.P("p := new(", enum.GoIdent, ")")
261 g.P("*p = x")
262 g.P("return p")
263 g.P("}")
264 g.P()
265 }
266 g.P("func (x ", enum.GoIdent, ") String() string {")
267 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
268 g.P("}")
269 g.P()
270
271 if enum.Desc.Syntax() != protoreflect.Proto3 {
272 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
273 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
274 g.P("if err != nil {")
275 g.P("return err")
276 g.P("}")
277 g.P("*x = ", enum.GoIdent, "(value)")
278 g.P("return nil")
279 g.P("}")
280 g.P()
281 }
282
283 var indexes []string
284 for i := 1; i < len(enum.Path); i += 2 {
285 indexes = append(indexes, strconv.Itoa(int(enum.Path[i])))
286 }
287 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
288 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
289 g.P("}")
290 g.P()
291
292 genWellKnownType(g, enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700293}
294
Damien Neil658051b2018-09-10 12:26:21 -0700295// enumRegistryName returns the name used to register an enum with the proto
296// package registry.
297//
298// Confusingly, this is <proto_package>.<go_ident>. This probably should have
299// been the full name of the proto enum type instead, but changing it at this
300// point would require thought.
301func enumRegistryName(enum *protogen.Enum) string {
302 // Find the FileDescriptor for this enum.
303 var desc protoreflect.Descriptor = enum.Desc
304 for {
305 p, ok := desc.Parent()
306 if !ok {
307 break
308 }
309 desc = p
310 }
311 fdesc := desc.(protoreflect.FileDescriptor)
312 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
313}
314
Damien Neilcab8dfe2018-09-06 14:51:28 -0700315func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700316 if message.Desc.IsMapEntry() {
317 return
318 }
319
Damien Neilcab8dfe2018-09-06 14:51:28 -0700320 genComment(g, f, message.Path)
Damien Neil658051b2018-09-10 12:26:21 -0700321 // TODO: deprecation
Damien Neilcab8dfe2018-09-06 14:51:28 -0700322 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700323 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700324 if field.OneofType != nil {
325 // It would be a bit simpler to iterate over the oneofs below,
326 // but generating the field here keeps the contents of the Go
327 // struct in the same order as the contents of the source
328 // .proto file.
329 if field == field.OneofType.Fields[0] {
330 genOneofField(gen, g, f, message, field.OneofType)
331 }
Damien Neil658051b2018-09-10 12:26:21 -0700332 continue
333 }
334 genComment(g, f, field.Path)
Damien Neil77f82fe2018-09-13 10:59:17 -0700335 goType, pointer := fieldGoType(g, field)
336 if pointer {
337 goType = "*" + goType
338 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700339 tags := []string{
340 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
341 fmt.Sprintf("json:%q", fieldJSONTag(field)),
342 }
343 if field.Desc.IsMap() {
344 key := field.MessageType.Fields[0]
345 val := field.MessageType.Fields[1]
346 tags = append(tags,
347 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
348 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
349 )
350 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700351 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
Damien Neil658051b2018-09-10 12:26:21 -0700352 }
353 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700354
355 if message.Desc.ExtensionRanges().Len() > 0 {
356 var tags []string
357 if messageOptions(gen, message).GetMessageSetWireFormat() {
358 tags = append(tags, `protobuf_messageset:"1"`)
359 }
360 tags = append(tags, `json:"-"`)
361 g.P(protogen.GoIdent{
362 GoImportPath: protoPackage,
363 GoName: "XXX_InternalExtensions",
364 }, " `", strings.Join(tags, " "), "`")
365 }
Damien Neil658051b2018-09-10 12:26:21 -0700366 // TODO XXX_InternalExtensions
367 g.P("XXX_unrecognized []byte `json:\"-\"`")
368 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700369 g.P("}")
370 g.P()
371
Damien Neila1c6abc2018-09-12 13:36:34 -0700372 // Reset
373 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
374 // String
375 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
376 GoImportPath: protoPackage,
377 GoName: "CompactTextString",
378 }, "(m) }")
379 // ProtoMessage
380 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
381 // Descriptor
382 var indexes []string
383 for i := 1; i < len(message.Path); i += 2 {
384 indexes = append(indexes, strconv.Itoa(int(message.Path[i])))
385 }
386 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
387 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
388 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700389 g.P()
390
391 // ExtensionRangeArray
392 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
393 if messageOptions(gen, message).GetMessageSetWireFormat() {
394 g.P("func (m *", message.GoIdent, ") MarshalJSON() ([]byte, error) {")
395 g.P("return ", protogen.GoIdent{
396 GoImportPath: protoPackage,
397 GoName: "MarshalMessageSetJSON",
398 }, "(&m.XXX_InternalExtensions)")
399 g.P("}")
400 g.P("func (m *", message.GoIdent, ") UnmarshalJSON(buf []byte) error {")
401 g.P("return ", protogen.GoIdent{
402 GoImportPath: protoPackage,
403 GoName: "UnmarshalMessageSetJSON",
404 }, "(buf, &m.XXX_InternalExtensions)")
405 g.P("}")
406 g.P()
407 }
408
409 protoExtRange := protogen.GoIdent{
410 GoImportPath: protoPackage,
411 GoName: "ExtensionRange",
412 }
413 extRangeVar := "extRange_" + message.GoIdent.GoName
414 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
415 for i := 0; i < extranges.Len(); i++ {
416 r := extranges.Get(i)
417 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
418 }
419 g.P("}")
420 g.P()
421 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
422 g.P("return ", extRangeVar)
423 g.P("}")
424 g.P()
425 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700426
427 // Table-driven proto support.
428 //
429 // TODO: It does not scale to keep adding another method for every
430 // operation on protos that we want to switch over to using the
431 // table-driven approach. Instead, we should only add a single method
432 // that allows getting access to the *InternalMessageInfo struct and then
433 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
434 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
435 // XXX_Unmarshal
436 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
437 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
438 g.P("}")
439 // XXX_Marshal
440 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
441 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
442 g.P("}")
443 // XXX_Merge
444 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
445 g.P(messageInfoVar, ".Merge(m, src)")
446 g.P("}")
447 // XXX_Size
448 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
449 g.P("return ", messageInfoVar, ".Size(m)")
450 g.P("}")
451 // XXX_DiscardUnknown
452 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
453 g.P(messageInfoVar, ".DiscardUnknown(m)")
454 g.P("}")
455 g.P()
456 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
457 GoImportPath: protoPackage,
458 GoName: "InternalMessageInfo",
459 })
460 g.P()
461
Damien Neilebc699d2018-09-13 08:50:13 -0700462 // Constants and vars holding the default values of fields.
463 for _, field := range message.Fields {
464 if !field.Desc.HasDefault() {
465 continue
466 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700467 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700468 def := field.Desc.Default()
469 switch field.Desc.Kind() {
470 case protoreflect.StringKind:
471 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
472 case protoreflect.BytesKind:
473 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
474 case protoreflect.EnumKind:
475 enum := field.EnumType
476 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
477 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
478 case protoreflect.FloatKind, protoreflect.DoubleKind:
479 // Floating point numbers need extra handling for -Inf/Inf/NaN.
480 f := field.Desc.Default().Float()
481 goType := "float64"
482 if field.Desc.Kind() == protoreflect.FloatKind {
483 goType = "float32"
484 }
485 // funcCall returns a call to a function in the math package,
486 // possibly converting the result to float32.
487 funcCall := func(fn, param string) string {
488 s := g.QualifiedGoIdent(protogen.GoIdent{
489 GoImportPath: "math",
490 GoName: fn,
491 }) + param
492 if goType != "float64" {
493 s = goType + "(" + s + ")"
494 }
495 return s
496 }
497 switch {
498 case math.IsInf(f, -1):
499 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
500 case math.IsInf(f, 1):
501 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
502 case math.IsNaN(f):
503 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
504 default:
505 g.P("const ", defVarName, " ", goType, " = ", f)
506 }
507 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700508 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700509 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
510 }
511 }
512 g.P()
513
Damien Neil77f82fe2018-09-13 10:59:17 -0700514 // Getters.
515 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700516 if field.OneofType != nil {
517 if field == field.OneofType.Fields[0] {
518 genOneofTypes(gen, g, f, message, field.OneofType)
519 }
520 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700521 goType, pointer := fieldGoType(g, field)
522 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil1fa78d82018-09-13 13:12:36 -0700523 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
524 if field.OneofType != nil {
525 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", message.GoIdent.GoName, "_", field.GoName, "); ok {")
526 g.P("return x.", field.GoName)
527 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700528 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700529 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
530 g.P("if m != nil {")
531 } else {
532 g.P("if m != nil && m.", field.GoName, " != nil {")
533 }
534 star := ""
535 if pointer {
536 star = "*"
537 }
538 g.P("return ", star, " m.", field.GoName)
539 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700540 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700541 g.P("return ", defaultValue)
542 g.P("}")
543 g.P()
544 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700545
Damien Neilce36f8d2018-09-13 15:19:08 -0700546 genWellKnownType(g, message.GoIdent, message.Desc)
Damien Neil1fa78d82018-09-13 13:12:36 -0700547
548 if len(message.Oneofs) > 0 {
549 genOneofFuncs(gen, g, f, message)
550 }
Damien Neil993c04d2018-09-14 15:41:11 -0700551 for _, extension := range message.Extensions {
552 genExtension(gen, g, f, extension)
553 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700554}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700555
Damien Neil77f82fe2018-09-13 10:59:17 -0700556// fieldGoType returns the Go type used for a field.
557//
558// If it returns pointer=true, the struct field is a pointer to the type.
559func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700560 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700561 switch field.Desc.Kind() {
562 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700563 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700564 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700565 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700566 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700567 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700568 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700569 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700570 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700571 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700572 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700573 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700574 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700575 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700576 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700577 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700578 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700579 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700580 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700581 goType = "[]byte"
582 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700583 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700584 if field.Desc.IsMap() {
585 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
586 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
587 return fmt.Sprintf("map[%v]%v", keyType, valType), false
588 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700589 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
590 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700591 }
592 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700593 goType = "[]" + goType
594 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700595 }
596 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700597 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700598 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700599 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700600}
601
602func fieldProtobufTag(field *protogen.Field) string {
603 var tag []string
604 // wire type
605 tag = append(tag, wireTypes[field.Desc.Kind()])
606 // field number
607 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
608 // cardinality
609 switch field.Desc.Cardinality() {
610 case protoreflect.Optional:
611 tag = append(tag, "opt")
612 case protoreflect.Required:
613 tag = append(tag, "req")
614 case protoreflect.Repeated:
615 tag = append(tag, "rep")
616 }
Damien Neil658051b2018-09-10 12:26:21 -0700617 // TODO: packed
618 // name
619 name := string(field.Desc.Name())
620 if field.Desc.Kind() == protoreflect.GroupKind {
621 // The name of the FieldDescriptor for a group field is
622 // lowercased. To find the original capitalization, we
623 // look in the field's MessageType.
624 name = string(field.MessageType.Desc.Name())
625 }
626 tag = append(tag, "name="+name)
627 // JSON name
628 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
629 tag = append(tag, "json="+jsonName)
630 }
631 // proto3
632 if field.Desc.Syntax() == protoreflect.Proto3 {
633 tag = append(tag, "proto3")
634 }
635 // enum
636 if field.Desc.Kind() == protoreflect.EnumKind {
637 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
638 }
639 // oneof
640 if field.Desc.OneofType() != nil {
641 tag = append(tag, "oneof")
642 }
Damien Neilebc699d2018-09-13 08:50:13 -0700643 // default value
644 // This must appear last in the tag, since commas in strings aren't escaped.
645 if field.Desc.HasDefault() {
646 var def string
647 switch field.Desc.Kind() {
648 case protoreflect.BoolKind:
649 if field.Desc.Default().Bool() {
650 def = "1"
651 } else {
652 def = "0"
653 }
654 case protoreflect.BytesKind:
655 def = string(field.Desc.Default().Bytes())
656 case protoreflect.FloatKind, protoreflect.DoubleKind:
657 f := field.Desc.Default().Float()
658 switch {
659 case math.IsInf(f, -1):
660 def = "-inf"
661 case math.IsInf(f, 1):
662 def = "inf"
663 case math.IsNaN(f):
664 def = "nan"
665 default:
666 def = fmt.Sprint(f)
667 }
668 default:
669 def = fmt.Sprint(field.Desc.Default().Interface())
670 }
671 tag = append(tag, "def="+def)
672 }
Damien Neil658051b2018-09-10 12:26:21 -0700673 return strings.Join(tag, ",")
674}
675
Damien Neil77f82fe2018-09-13 10:59:17 -0700676func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
677 if field.Desc.Cardinality() == protoreflect.Repeated {
678 return "nil"
679 }
680 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700681 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700682 if field.Desc.Kind() == protoreflect.BytesKind {
683 return "append([]byte(nil), " + defVarName + "...)"
684 }
685 return defVarName
686 }
687 switch field.Desc.Kind() {
688 case protoreflect.BoolKind:
689 return "false"
690 case protoreflect.StringKind:
691 return `""`
692 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
693 return "nil"
694 case protoreflect.EnumKind:
695 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
696 default:
697 return "0"
698 }
699}
700
Damien Neil658051b2018-09-10 12:26:21 -0700701var wireTypes = map[protoreflect.Kind]string{
702 protoreflect.BoolKind: "varint",
703 protoreflect.EnumKind: "varint",
704 protoreflect.Int32Kind: "varint",
705 protoreflect.Sint32Kind: "zigzag32",
706 protoreflect.Uint32Kind: "varint",
707 protoreflect.Int64Kind: "varint",
708 protoreflect.Sint64Kind: "zigzag64",
709 protoreflect.Uint64Kind: "varint",
710 protoreflect.Sfixed32Kind: "fixed32",
711 protoreflect.Fixed32Kind: "fixed32",
712 protoreflect.FloatKind: "fixed32",
713 protoreflect.Sfixed64Kind: "fixed64",
714 protoreflect.Fixed64Kind: "fixed64",
715 protoreflect.DoubleKind: "fixed64",
716 protoreflect.StringKind: "bytes",
717 protoreflect.BytesKind: "bytes",
718 protoreflect.MessageKind: "bytes",
719 protoreflect.GroupKind: "group",
720}
721
722func fieldJSONTag(field *protogen.Field) string {
723 return string(field.Desc.Name()) + ",omitempty"
724}
725
Damien Neil993c04d2018-09-14 15:41:11 -0700726func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, extension *protogen.Extension) {
727 g.P("var ", extensionVar(f, extension), " = &", protogen.GoIdent{
728 GoImportPath: protoPackage,
729 GoName: "ExtensionDesc",
730 }, "{")
731 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
732 goType, pointer := fieldGoType(g, extension)
733 if pointer {
734 goType = "*" + goType
735 }
736 g.P("ExtensionType: (", goType, ")(nil),")
737 g.P("Field: ", extension.Desc.Number(), ",")
738 g.P("Name: ", strconv.Quote(string(extension.Desc.FullName())), ",")
739 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
740 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
741 g.P("}")
742 g.P()
743}
744
745// extensionVar returns the var holding the ExtensionDesc for an extension.
746func extensionVar(f *File, extension *protogen.Extension) protogen.GoIdent {
747 name := "E_"
748 if extension.ParentMessage != nil {
749 name += extension.ParentMessage.GoIdent.GoName + "_"
750 }
751 name += extension.GoName
752 return protogen.GoIdent{
753 GoImportPath: f.GoImportPath,
754 GoName: name,
755 }
756}
757
Damien Neilce36f8d2018-09-13 15:19:08 -0700758// genInitFunction generates an init function that registers the types in the
759// generated file with the proto package.
760func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil993c04d2018-09-14 15:41:11 -0700761 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700762 return
763 }
764
765 g.P("func init() {")
766 for _, message := range f.allMessages {
767 if message.Desc.IsMapEntry() {
768 continue
769 }
770
771 name := message.GoIdent.GoName
772 g.P(protogen.GoIdent{
773 GoImportPath: protoPackage,
774 GoName: "RegisterType",
775 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
776
777 // Types of map fields, sorted by the name of the field message type.
778 var mapFields []*protogen.Field
779 for _, field := range message.Fields {
780 if field.Desc.IsMap() {
781 mapFields = append(mapFields, field)
782 }
783 }
784 sort.Slice(mapFields, func(i, j int) bool {
785 ni := mapFields[i].MessageType.Desc.FullName()
786 nj := mapFields[j].MessageType.Desc.FullName()
787 return ni < nj
788 })
789 for _, field := range mapFields {
790 typeName := string(field.MessageType.Desc.FullName())
791 goType, _ := fieldGoType(g, field)
792 g.P(protogen.GoIdent{
793 GoImportPath: protoPackage,
794 GoName: "RegisterMapType",
795 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
796 }
797 }
798 for _, enum := range f.allEnums {
799 name := enum.GoIdent.GoName
800 g.P(protogen.GoIdent{
801 GoImportPath: protoPackage,
802 GoName: "RegisterEnum",
803 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
804 }
Damien Neil993c04d2018-09-14 15:41:11 -0700805 for _, extension := range f.allExtensions {
806 g.P(protogen.GoIdent{
807 GoImportPath: protoPackage,
808 GoName: "RegisterExtension",
809 }, "(", extensionVar(f, extension), ")")
810 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700811 g.P("}")
812 g.P()
813}
814
Damien Neil1fa78d82018-09-13 13:12:36 -0700815func genComment(g *protogen.GeneratedFile, f *File, path []int32) (hasComment bool) {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700816 for _, loc := range f.locationMap[pathKey(path)] {
817 if loc.LeadingComments == nil {
818 continue
819 }
820 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
Damien Neil1fa78d82018-09-13 13:12:36 -0700821 hasComment = true
Damien Neilcab8dfe2018-09-06 14:51:28 -0700822 g.P("//", line)
823 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700824 break
Damien Neilcab8dfe2018-09-06 14:51:28 -0700825 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700826 return hasComment
Damien Neilcab8dfe2018-09-06 14:51:28 -0700827}
828
829// pathKey converts a location path to a string suitable for use as a map key.
830func pathKey(path []int32) string {
831 var buf []byte
832 for i, x := range path {
833 if i != 0 {
834 buf = append(buf, ',')
835 }
836 buf = strconv.AppendInt(buf, int64(x), 10)
837 }
838 return string(buf)
839}
Damien Neil46abb572018-09-07 12:45:37 -0700840
841func genWellKnownType(g *protogen.GeneratedFile, ident protogen.GoIdent, desc protoreflect.Descriptor) {
842 if wellKnownTypes[desc.FullName()] {
843 g.P("func (", ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
844 g.P()
845 }
846}
847
848// Names of messages and enums for which we will generate XXX_WellKnownType methods.
849var wellKnownTypes = map[protoreflect.FullName]bool{
850 "google.protobuf.NullValue": true,
851}