blob: a03ae3673b9bdee23ba0202ca22f57d4f890e948 [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 Neilcab8dfe2018-09-06 14:51:28 -070059}
60
61func genFile(gen *protogen.Plugin, file *protogen.File) {
62 f := &File{
63 File: file,
64 locationMap: make(map[string][]*descpb.SourceCodeInfo_Location),
65 }
66 for _, loc := range file.Proto.GetSourceCodeInfo().GetLocation() {
67 key := pathKey(loc.Path)
68 f.locationMap[key] = append(f.locationMap[key], loc)
69 }
70
Damien Neilce36f8d2018-09-13 15:19:08 -070071 f.allEnums = append(f.allEnums, f.File.Enums...)
72 f.allMessages = append(f.allMessages, f.File.Messages...)
73 for _, message := range f.Messages {
74 f.initMessage(message)
75 }
76
Damien Neil46abb572018-09-07 12:45:37 -070077 // Determine the name of the var holding the file descriptor:
78 //
79 // fileDescriptor_<hash of filename>
80 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
81 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
82
Damien Neil082ce922018-09-06 10:23:53 -070083 g := gen.NewGeneratedFile(f.GeneratedFilenamePrefix+".pb.go", f.GoImportPath)
Damien Neil220c2022018-08-15 11:24:18 -070084 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neilabc6fc12018-08-23 14:39:30 -070085 g.P("// source: ", f.Desc.Path())
Damien Neil220c2022018-08-15 11:24:18 -070086 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070087 const filePackageField = 2 // FileDescriptorProto.package
88 genComment(g, f, []int32{filePackageField})
89 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070090 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070091 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -070092
93 // These references are not necessary, since we automatically add
94 // all necessary imports before formatting the generated file.
95 //
96 // This section exists to generate output more consistent with
97 // the previous version of protoc-gen-go, to make it easier to
98 // detect unintended variations.
99 //
100 // TODO: Eventually remove this.
101 g.P("// Reference imports to suppress errors if they are not otherwise used.")
102 g.P("var _ = ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "Marshal"})
103 g.P("var _ = ", protogen.GoIdent{GoImportPath: "fmt", GoName: "Errorf"})
104 g.P("var _ = ", protogen.GoIdent{GoImportPath: "math", GoName: "Inf"})
105 g.P()
106
Damien Neild4127922018-09-12 11:13:49 -0700107 g.P("// This is a compile-time assertion to ensure that this generated file")
108 g.P("// is compatible with the proto package it is being compiled against.")
109 g.P("// A compilation error at this line likely means your copy of the")
110 g.P("// proto package needs to be updated.")
111 g.P("const _ = ", protogen.GoIdent{
112 GoImportPath: protoPackage,
113 GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion),
114 }, "// please upgrade the proto package")
115 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700116
Damien Neilce36f8d2018-09-13 15:19:08 -0700117 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700118 genEnum(gen, g, f, enum)
119 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700120 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700121 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700122 }
Damien Neil220c2022018-08-15 11:24:18 -0700123
Damien Neilce36f8d2018-09-13 15:19:08 -0700124 genInitFunction(gen, g, f)
Damien Neil46abb572018-09-07 12:45:37 -0700125
Damien Neil7779e052018-09-07 14:14:06 -0700126 genFileDescriptor(gen, g, f)
127}
128
Damien Neilce36f8d2018-09-13 15:19:08 -0700129func (f *File) initMessage(message *protogen.Message) {
130 f.allEnums = append(f.allEnums, message.Enums...)
131 f.allMessages = append(f.allMessages, message.Messages...)
132 for _, m := range message.Messages {
133 f.initMessage(m)
134 }
135}
136
Damien Neilcab8dfe2018-09-06 14:51:28 -0700137func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil7779e052018-09-07 14:14:06 -0700138 // Trim the source_code_info from the descriptor.
139 // Marshal and gzip it.
140 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
141 descProto.SourceCodeInfo = nil
142 b, err := proto.Marshal(descProto)
143 if err != nil {
144 gen.Error(err)
145 return
146 }
147 var buf bytes.Buffer
148 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
149 w.Write(b)
150 w.Close()
151 b = buf.Bytes()
152
Damien Neil46abb572018-09-07 12:45:37 -0700153 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700154 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700155 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700156 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
157 for len(b) > 0 {
158 n := 16
159 if n > len(b) {
160 n = len(b)
161 }
162
163 s := ""
164 for _, c := range b[:n] {
165 s += fmt.Sprintf("0x%02x,", c)
166 }
167 g.P(s)
168
169 b = b[n:]
170 }
171 g.P("}")
172 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700173}
Damien Neilc7d07d92018-08-22 13:46:02 -0700174
Damien Neil46abb572018-09-07 12:45:37 -0700175func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, enum *protogen.Enum) {
176 genComment(g, f, enum.Path)
177 // TODO: deprecation
178 g.P("type ", enum.GoIdent, " int32")
179 g.P("const (")
180 for _, value := range enum.Values {
181 genComment(g, f, value.Path)
182 // TODO: deprecation
183 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number())
184 }
185 g.P(")")
186 g.P()
187 nameMap := enum.GoIdent.GoName + "_name"
188 g.P("var ", nameMap, " = map[int32]string{")
189 generated := make(map[protoreflect.EnumNumber]bool)
190 for _, value := range enum.Values {
191 duplicate := ""
192 if _, present := generated[value.Desc.Number()]; present {
193 duplicate = "// Duplicate value: "
194 }
195 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
196 generated[value.Desc.Number()] = true
197 }
198 g.P("}")
199 g.P()
200 valueMap := enum.GoIdent.GoName + "_value"
201 g.P("var ", valueMap, " = map[string]int32{")
202 for _, value := range enum.Values {
203 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
204 }
205 g.P("}")
206 g.P()
207 if enum.Desc.Syntax() != protoreflect.Proto3 {
208 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
209 g.P("p := new(", enum.GoIdent, ")")
210 g.P("*p = x")
211 g.P("return p")
212 g.P("}")
213 g.P()
214 }
215 g.P("func (x ", enum.GoIdent, ") String() string {")
216 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
217 g.P("}")
218 g.P()
219
220 if enum.Desc.Syntax() != protoreflect.Proto3 {
221 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
222 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
223 g.P("if err != nil {")
224 g.P("return err")
225 g.P("}")
226 g.P("*x = ", enum.GoIdent, "(value)")
227 g.P("return nil")
228 g.P("}")
229 g.P()
230 }
231
232 var indexes []string
233 for i := 1; i < len(enum.Path); i += 2 {
234 indexes = append(indexes, strconv.Itoa(int(enum.Path[i])))
235 }
236 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
237 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
238 g.P("}")
239 g.P()
240
241 genWellKnownType(g, enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700242}
243
Damien Neil658051b2018-09-10 12:26:21 -0700244// enumRegistryName returns the name used to register an enum with the proto
245// package registry.
246//
247// Confusingly, this is <proto_package>.<go_ident>. This probably should have
248// been the full name of the proto enum type instead, but changing it at this
249// point would require thought.
250func enumRegistryName(enum *protogen.Enum) string {
251 // Find the FileDescriptor for this enum.
252 var desc protoreflect.Descriptor = enum.Desc
253 for {
254 p, ok := desc.Parent()
255 if !ok {
256 break
257 }
258 desc = p
259 }
260 fdesc := desc.(protoreflect.FileDescriptor)
261 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
262}
263
Damien Neilcab8dfe2018-09-06 14:51:28 -0700264func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700265 if message.Desc.IsMapEntry() {
266 return
267 }
268
Damien Neilcab8dfe2018-09-06 14:51:28 -0700269 genComment(g, f, message.Path)
Damien Neil658051b2018-09-10 12:26:21 -0700270 // TODO: deprecation
Damien Neilcab8dfe2018-09-06 14:51:28 -0700271 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700272 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700273 if field.OneofType != nil {
274 // It would be a bit simpler to iterate over the oneofs below,
275 // but generating the field here keeps the contents of the Go
276 // struct in the same order as the contents of the source
277 // .proto file.
278 if field == field.OneofType.Fields[0] {
279 genOneofField(gen, g, f, message, field.OneofType)
280 }
Damien Neil658051b2018-09-10 12:26:21 -0700281 continue
282 }
283 genComment(g, f, field.Path)
Damien Neil77f82fe2018-09-13 10:59:17 -0700284 goType, pointer := fieldGoType(g, field)
285 if pointer {
286 goType = "*" + goType
287 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700288 tags := []string{
289 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
290 fmt.Sprintf("json:%q", fieldJSONTag(field)),
291 }
292 if field.Desc.IsMap() {
293 key := field.MessageType.Fields[0]
294 val := field.MessageType.Fields[1]
295 tags = append(tags,
296 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
297 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
298 )
299 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700300 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
Damien Neil658051b2018-09-10 12:26:21 -0700301 }
302 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
303 // TODO XXX_InternalExtensions
304 g.P("XXX_unrecognized []byte `json:\"-\"`")
305 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700306 g.P("}")
307 g.P()
308
Damien Neila1c6abc2018-09-12 13:36:34 -0700309 // Reset
310 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
311 // String
312 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
313 GoImportPath: protoPackage,
314 GoName: "CompactTextString",
315 }, "(m) }")
316 // ProtoMessage
317 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
318 // Descriptor
319 var indexes []string
320 for i := 1; i < len(message.Path); i += 2 {
321 indexes = append(indexes, strconv.Itoa(int(message.Path[i])))
322 }
323 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
324 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
325 g.P("}")
326 // TODO: extension support methods
327
328 // Table-driven proto support.
329 //
330 // TODO: It does not scale to keep adding another method for every
331 // operation on protos that we want to switch over to using the
332 // table-driven approach. Instead, we should only add a single method
333 // that allows getting access to the *InternalMessageInfo struct and then
334 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
335 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
336 // XXX_Unmarshal
337 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
338 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
339 g.P("}")
340 // XXX_Marshal
341 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
342 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
343 g.P("}")
344 // XXX_Merge
345 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
346 g.P(messageInfoVar, ".Merge(m, src)")
347 g.P("}")
348 // XXX_Size
349 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
350 g.P("return ", messageInfoVar, ".Size(m)")
351 g.P("}")
352 // XXX_DiscardUnknown
353 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
354 g.P(messageInfoVar, ".DiscardUnknown(m)")
355 g.P("}")
356 g.P()
357 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
358 GoImportPath: protoPackage,
359 GoName: "InternalMessageInfo",
360 })
361 g.P()
362
Damien Neilebc699d2018-09-13 08:50:13 -0700363 // Constants and vars holding the default values of fields.
364 for _, field := range message.Fields {
365 if !field.Desc.HasDefault() {
366 continue
367 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700368 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700369 def := field.Desc.Default()
370 switch field.Desc.Kind() {
371 case protoreflect.StringKind:
372 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
373 case protoreflect.BytesKind:
374 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
375 case protoreflect.EnumKind:
376 enum := field.EnumType
377 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
378 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
379 case protoreflect.FloatKind, protoreflect.DoubleKind:
380 // Floating point numbers need extra handling for -Inf/Inf/NaN.
381 f := field.Desc.Default().Float()
382 goType := "float64"
383 if field.Desc.Kind() == protoreflect.FloatKind {
384 goType = "float32"
385 }
386 // funcCall returns a call to a function in the math package,
387 // possibly converting the result to float32.
388 funcCall := func(fn, param string) string {
389 s := g.QualifiedGoIdent(protogen.GoIdent{
390 GoImportPath: "math",
391 GoName: fn,
392 }) + param
393 if goType != "float64" {
394 s = goType + "(" + s + ")"
395 }
396 return s
397 }
398 switch {
399 case math.IsInf(f, -1):
400 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
401 case math.IsInf(f, 1):
402 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
403 case math.IsNaN(f):
404 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
405 default:
406 g.P("const ", defVarName, " ", goType, " = ", f)
407 }
408 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700409 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700410 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
411 }
412 }
413 g.P()
414
Damien Neil77f82fe2018-09-13 10:59:17 -0700415 // Getters.
416 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700417 if field.OneofType != nil {
418 if field == field.OneofType.Fields[0] {
419 genOneofTypes(gen, g, f, message, field.OneofType)
420 }
421 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700422 goType, pointer := fieldGoType(g, field)
423 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil1fa78d82018-09-13 13:12:36 -0700424 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
425 if field.OneofType != nil {
426 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", message.GoIdent.GoName, "_", field.GoName, "); ok {")
427 g.P("return x.", field.GoName)
428 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700429 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700430 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
431 g.P("if m != nil {")
432 } else {
433 g.P("if m != nil && m.", field.GoName, " != nil {")
434 }
435 star := ""
436 if pointer {
437 star = "*"
438 }
439 g.P("return ", star, " m.", field.GoName)
440 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700441 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700442 g.P("return ", defaultValue)
443 g.P("}")
444 g.P()
445 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700446
Damien Neilce36f8d2018-09-13 15:19:08 -0700447 genWellKnownType(g, message.GoIdent, message.Desc)
Damien Neil1fa78d82018-09-13 13:12:36 -0700448
449 if len(message.Oneofs) > 0 {
450 genOneofFuncs(gen, g, f, message)
451 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700452}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700453
Damien Neil77f82fe2018-09-13 10:59:17 -0700454// fieldGoType returns the Go type used for a field.
455//
456// If it returns pointer=true, the struct field is a pointer to the type.
457func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700458 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700459 switch field.Desc.Kind() {
460 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700461 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700462 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700463 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700464 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700465 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700466 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700467 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700468 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700469 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700470 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700471 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700472 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700473 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700474 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700475 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700476 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700477 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700478 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700479 goType = "[]byte"
480 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700481 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700482 if field.Desc.IsMap() {
483 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
484 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
485 return fmt.Sprintf("map[%v]%v", keyType, valType), false
486 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700487 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
488 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700489 }
490 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700491 goType = "[]" + goType
492 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700493 }
494 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700495 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700496 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700497 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700498}
499
500func fieldProtobufTag(field *protogen.Field) string {
501 var tag []string
502 // wire type
503 tag = append(tag, wireTypes[field.Desc.Kind()])
504 // field number
505 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
506 // cardinality
507 switch field.Desc.Cardinality() {
508 case protoreflect.Optional:
509 tag = append(tag, "opt")
510 case protoreflect.Required:
511 tag = append(tag, "req")
512 case protoreflect.Repeated:
513 tag = append(tag, "rep")
514 }
Damien Neil658051b2018-09-10 12:26:21 -0700515 // TODO: packed
516 // name
517 name := string(field.Desc.Name())
518 if field.Desc.Kind() == protoreflect.GroupKind {
519 // The name of the FieldDescriptor for a group field is
520 // lowercased. To find the original capitalization, we
521 // look in the field's MessageType.
522 name = string(field.MessageType.Desc.Name())
523 }
524 tag = append(tag, "name="+name)
525 // JSON name
526 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
527 tag = append(tag, "json="+jsonName)
528 }
529 // proto3
530 if field.Desc.Syntax() == protoreflect.Proto3 {
531 tag = append(tag, "proto3")
532 }
533 // enum
534 if field.Desc.Kind() == protoreflect.EnumKind {
535 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
536 }
537 // oneof
538 if field.Desc.OneofType() != nil {
539 tag = append(tag, "oneof")
540 }
Damien Neilebc699d2018-09-13 08:50:13 -0700541 // default value
542 // This must appear last in the tag, since commas in strings aren't escaped.
543 if field.Desc.HasDefault() {
544 var def string
545 switch field.Desc.Kind() {
546 case protoreflect.BoolKind:
547 if field.Desc.Default().Bool() {
548 def = "1"
549 } else {
550 def = "0"
551 }
552 case protoreflect.BytesKind:
553 def = string(field.Desc.Default().Bytes())
554 case protoreflect.FloatKind, protoreflect.DoubleKind:
555 f := field.Desc.Default().Float()
556 switch {
557 case math.IsInf(f, -1):
558 def = "-inf"
559 case math.IsInf(f, 1):
560 def = "inf"
561 case math.IsNaN(f):
562 def = "nan"
563 default:
564 def = fmt.Sprint(f)
565 }
566 default:
567 def = fmt.Sprint(field.Desc.Default().Interface())
568 }
569 tag = append(tag, "def="+def)
570 }
Damien Neil658051b2018-09-10 12:26:21 -0700571 return strings.Join(tag, ",")
572}
573
Damien Neil77f82fe2018-09-13 10:59:17 -0700574func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
575 if field.Desc.Cardinality() == protoreflect.Repeated {
576 return "nil"
577 }
578 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700579 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700580 if field.Desc.Kind() == protoreflect.BytesKind {
581 return "append([]byte(nil), " + defVarName + "...)"
582 }
583 return defVarName
584 }
585 switch field.Desc.Kind() {
586 case protoreflect.BoolKind:
587 return "false"
588 case protoreflect.StringKind:
589 return `""`
590 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
591 return "nil"
592 case protoreflect.EnumKind:
593 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
594 default:
595 return "0"
596 }
597}
598
Damien Neil658051b2018-09-10 12:26:21 -0700599var wireTypes = map[protoreflect.Kind]string{
600 protoreflect.BoolKind: "varint",
601 protoreflect.EnumKind: "varint",
602 protoreflect.Int32Kind: "varint",
603 protoreflect.Sint32Kind: "zigzag32",
604 protoreflect.Uint32Kind: "varint",
605 protoreflect.Int64Kind: "varint",
606 protoreflect.Sint64Kind: "zigzag64",
607 protoreflect.Uint64Kind: "varint",
608 protoreflect.Sfixed32Kind: "fixed32",
609 protoreflect.Fixed32Kind: "fixed32",
610 protoreflect.FloatKind: "fixed32",
611 protoreflect.Sfixed64Kind: "fixed64",
612 protoreflect.Fixed64Kind: "fixed64",
613 protoreflect.DoubleKind: "fixed64",
614 protoreflect.StringKind: "bytes",
615 protoreflect.BytesKind: "bytes",
616 protoreflect.MessageKind: "bytes",
617 protoreflect.GroupKind: "group",
618}
619
620func fieldJSONTag(field *protogen.Field) string {
621 return string(field.Desc.Name()) + ",omitempty"
622}
623
Damien Neilce36f8d2018-09-13 15:19:08 -0700624// genInitFunction generates an init function that registers the types in the
625// generated file with the proto package.
626func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
627 if len(f.allMessages) == 0 && len(f.allEnums) == 0 {
628 return
629 }
630
631 g.P("func init() {")
632 for _, message := range f.allMessages {
633 if message.Desc.IsMapEntry() {
634 continue
635 }
636
637 name := message.GoIdent.GoName
638 g.P(protogen.GoIdent{
639 GoImportPath: protoPackage,
640 GoName: "RegisterType",
641 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
642
643 // Types of map fields, sorted by the name of the field message type.
644 var mapFields []*protogen.Field
645 for _, field := range message.Fields {
646 if field.Desc.IsMap() {
647 mapFields = append(mapFields, field)
648 }
649 }
650 sort.Slice(mapFields, func(i, j int) bool {
651 ni := mapFields[i].MessageType.Desc.FullName()
652 nj := mapFields[j].MessageType.Desc.FullName()
653 return ni < nj
654 })
655 for _, field := range mapFields {
656 typeName := string(field.MessageType.Desc.FullName())
657 goType, _ := fieldGoType(g, field)
658 g.P(protogen.GoIdent{
659 GoImportPath: protoPackage,
660 GoName: "RegisterMapType",
661 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
662 }
663 }
664 for _, enum := range f.allEnums {
665 name := enum.GoIdent.GoName
666 g.P(protogen.GoIdent{
667 GoImportPath: protoPackage,
668 GoName: "RegisterEnum",
669 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
670 }
671 g.P("}")
672 g.P()
673}
674
Damien Neil1fa78d82018-09-13 13:12:36 -0700675func genComment(g *protogen.GeneratedFile, f *File, path []int32) (hasComment bool) {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700676 for _, loc := range f.locationMap[pathKey(path)] {
677 if loc.LeadingComments == nil {
678 continue
679 }
680 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
Damien Neil1fa78d82018-09-13 13:12:36 -0700681 hasComment = true
Damien Neilcab8dfe2018-09-06 14:51:28 -0700682 g.P("//", line)
683 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700684 break
Damien Neilcab8dfe2018-09-06 14:51:28 -0700685 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700686 return hasComment
Damien Neilcab8dfe2018-09-06 14:51:28 -0700687}
688
689// pathKey converts a location path to a string suitable for use as a map key.
690func pathKey(path []int32) string {
691 var buf []byte
692 for i, x := range path {
693 if i != 0 {
694 buf = append(buf, ',')
695 }
696 buf = strconv.AppendInt(buf, int64(x), 10)
697 }
698 return string(buf)
699}
Damien Neil46abb572018-09-07 12:45:37 -0700700
701func genWellKnownType(g *protogen.GeneratedFile, ident protogen.GoIdent, desc protoreflect.Descriptor) {
702 if wellKnownTypes[desc.FullName()] {
703 g.P("func (", ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
704 g.P()
705 }
706}
707
708// Names of messages and enums for which we will generate XXX_WellKnownType methods.
709var wellKnownTypes = map[protoreflect.FullName]bool{
710 "google.protobuf.NullValue": true,
711}