blob: a6bc626ad14538aced892286c78d87a1ff883033 [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 {
273 if field.Desc.OneofType() != nil {
274 // TODO oneofs
275 continue
276 }
277 genComment(g, f, field.Path)
Damien Neil77f82fe2018-09-13 10:59:17 -0700278 goType, pointer := fieldGoType(g, field)
279 if pointer {
280 goType = "*" + goType
281 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700282 tags := []string{
283 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
284 fmt.Sprintf("json:%q", fieldJSONTag(field)),
285 }
286 if field.Desc.IsMap() {
287 key := field.MessageType.Fields[0]
288 val := field.MessageType.Fields[1]
289 tags = append(tags,
290 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
291 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
292 )
293 }
294 g.P(field.GoIdent, " ", goType, " `", strings.Join(tags, " "), "`")
Damien Neil658051b2018-09-10 12:26:21 -0700295 }
296 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
297 // TODO XXX_InternalExtensions
298 g.P("XXX_unrecognized []byte `json:\"-\"`")
299 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700300 g.P("}")
301 g.P()
302
Damien Neila1c6abc2018-09-12 13:36:34 -0700303 // Reset
304 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
305 // String
306 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
307 GoImportPath: protoPackage,
308 GoName: "CompactTextString",
309 }, "(m) }")
310 // ProtoMessage
311 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
312 // Descriptor
313 var indexes []string
314 for i := 1; i < len(message.Path); i += 2 {
315 indexes = append(indexes, strconv.Itoa(int(message.Path[i])))
316 }
317 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
318 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
319 g.P("}")
320 // TODO: extension support methods
321
322 // Table-driven proto support.
323 //
324 // TODO: It does not scale to keep adding another method for every
325 // operation on protos that we want to switch over to using the
326 // table-driven approach. Instead, we should only add a single method
327 // that allows getting access to the *InternalMessageInfo struct and then
328 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
329 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
330 // XXX_Unmarshal
331 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
332 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
333 g.P("}")
334 // XXX_Marshal
335 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
336 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
337 g.P("}")
338 // XXX_Merge
339 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
340 g.P(messageInfoVar, ".Merge(m, src)")
341 g.P("}")
342 // XXX_Size
343 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
344 g.P("return ", messageInfoVar, ".Size(m)")
345 g.P("}")
346 // XXX_DiscardUnknown
347 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
348 g.P(messageInfoVar, ".DiscardUnknown(m)")
349 g.P("}")
350 g.P()
351 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
352 GoImportPath: protoPackage,
353 GoName: "InternalMessageInfo",
354 })
355 g.P()
356
Damien Neilebc699d2018-09-13 08:50:13 -0700357 // Constants and vars holding the default values of fields.
358 for _, field := range message.Fields {
359 if !field.Desc.HasDefault() {
360 continue
361 }
362 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoIdent.GoName
363 def := field.Desc.Default()
364 switch field.Desc.Kind() {
365 case protoreflect.StringKind:
366 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
367 case protoreflect.BytesKind:
368 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
369 case protoreflect.EnumKind:
370 enum := field.EnumType
371 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
372 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
373 case protoreflect.FloatKind, protoreflect.DoubleKind:
374 // Floating point numbers need extra handling for -Inf/Inf/NaN.
375 f := field.Desc.Default().Float()
376 goType := "float64"
377 if field.Desc.Kind() == protoreflect.FloatKind {
378 goType = "float32"
379 }
380 // funcCall returns a call to a function in the math package,
381 // possibly converting the result to float32.
382 funcCall := func(fn, param string) string {
383 s := g.QualifiedGoIdent(protogen.GoIdent{
384 GoImportPath: "math",
385 GoName: fn,
386 }) + param
387 if goType != "float64" {
388 s = goType + "(" + s + ")"
389 }
390 return s
391 }
392 switch {
393 case math.IsInf(f, -1):
394 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
395 case math.IsInf(f, 1):
396 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
397 case math.IsNaN(f):
398 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
399 default:
400 g.P("const ", defVarName, " ", goType, " = ", f)
401 }
402 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700403 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700404 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
405 }
406 }
407 g.P()
408
Damien Neil77f82fe2018-09-13 10:59:17 -0700409 // Getters.
410 for _, field := range message.Fields {
411 goType, pointer := fieldGoType(g, field)
412 defaultValue := fieldDefaultValue(g, message, field)
413 g.P("func (m *", message.GoIdent, ") Get", field.GoIdent, "() ", goType, " {")
414 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
415 g.P("if m != nil {")
416 } else {
417 g.P("if m != nil && m.", field.GoIdent, " != nil {")
418 }
419 star := ""
420 if pointer {
421 star = "*"
422 }
423 g.P("return ", star, " m.", field.GoIdent)
424 g.P("}")
425 g.P("return ", defaultValue)
426 g.P("}")
427 g.P()
428 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700429
Damien Neilce36f8d2018-09-13 15:19:08 -0700430 genWellKnownType(g, message.GoIdent, message.Desc)
Damien Neilc7d07d92018-08-22 13:46:02 -0700431}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700432
Damien Neil77f82fe2018-09-13 10:59:17 -0700433// fieldGoType returns the Go type used for a field.
434//
435// If it returns pointer=true, the struct field is a pointer to the type.
436func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700437 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700438 switch field.Desc.Kind() {
439 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700440 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700441 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700442 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700443 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700444 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700445 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700446 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700447 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700448 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700449 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700450 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700451 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700452 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700453 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700454 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700455 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700456 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700457 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700458 goType = "[]byte"
459 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700460 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700461 if field.Desc.IsMap() {
462 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
463 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
464 return fmt.Sprintf("map[%v]%v", keyType, valType), false
465 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700466 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
467 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700468 }
469 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700470 goType = "[]" + goType
471 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700472 }
473 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700474 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700475 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700476 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700477}
478
479func fieldProtobufTag(field *protogen.Field) string {
480 var tag []string
481 // wire type
482 tag = append(tag, wireTypes[field.Desc.Kind()])
483 // field number
484 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
485 // cardinality
486 switch field.Desc.Cardinality() {
487 case protoreflect.Optional:
488 tag = append(tag, "opt")
489 case protoreflect.Required:
490 tag = append(tag, "req")
491 case protoreflect.Repeated:
492 tag = append(tag, "rep")
493 }
Damien Neil658051b2018-09-10 12:26:21 -0700494 // TODO: packed
495 // name
496 name := string(field.Desc.Name())
497 if field.Desc.Kind() == protoreflect.GroupKind {
498 // The name of the FieldDescriptor for a group field is
499 // lowercased. To find the original capitalization, we
500 // look in the field's MessageType.
501 name = string(field.MessageType.Desc.Name())
502 }
503 tag = append(tag, "name="+name)
504 // JSON name
505 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
506 tag = append(tag, "json="+jsonName)
507 }
508 // proto3
509 if field.Desc.Syntax() == protoreflect.Proto3 {
510 tag = append(tag, "proto3")
511 }
512 // enum
513 if field.Desc.Kind() == protoreflect.EnumKind {
514 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
515 }
516 // oneof
517 if field.Desc.OneofType() != nil {
518 tag = append(tag, "oneof")
519 }
Damien Neilebc699d2018-09-13 08:50:13 -0700520 // default value
521 // This must appear last in the tag, since commas in strings aren't escaped.
522 if field.Desc.HasDefault() {
523 var def string
524 switch field.Desc.Kind() {
525 case protoreflect.BoolKind:
526 if field.Desc.Default().Bool() {
527 def = "1"
528 } else {
529 def = "0"
530 }
531 case protoreflect.BytesKind:
532 def = string(field.Desc.Default().Bytes())
533 case protoreflect.FloatKind, protoreflect.DoubleKind:
534 f := field.Desc.Default().Float()
535 switch {
536 case math.IsInf(f, -1):
537 def = "-inf"
538 case math.IsInf(f, 1):
539 def = "inf"
540 case math.IsNaN(f):
541 def = "nan"
542 default:
543 def = fmt.Sprint(f)
544 }
545 default:
546 def = fmt.Sprint(field.Desc.Default().Interface())
547 }
548 tag = append(tag, "def="+def)
549 }
Damien Neil658051b2018-09-10 12:26:21 -0700550 return strings.Join(tag, ",")
551}
552
Damien Neil77f82fe2018-09-13 10:59:17 -0700553func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
554 if field.Desc.Cardinality() == protoreflect.Repeated {
555 return "nil"
556 }
557 if field.Desc.HasDefault() {
558 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoIdent.GoName
559 if field.Desc.Kind() == protoreflect.BytesKind {
560 return "append([]byte(nil), " + defVarName + "...)"
561 }
562 return defVarName
563 }
564 switch field.Desc.Kind() {
565 case protoreflect.BoolKind:
566 return "false"
567 case protoreflect.StringKind:
568 return `""`
569 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
570 return "nil"
571 case protoreflect.EnumKind:
572 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
573 default:
574 return "0"
575 }
576}
577
Damien Neil658051b2018-09-10 12:26:21 -0700578var wireTypes = map[protoreflect.Kind]string{
579 protoreflect.BoolKind: "varint",
580 protoreflect.EnumKind: "varint",
581 protoreflect.Int32Kind: "varint",
582 protoreflect.Sint32Kind: "zigzag32",
583 protoreflect.Uint32Kind: "varint",
584 protoreflect.Int64Kind: "varint",
585 protoreflect.Sint64Kind: "zigzag64",
586 protoreflect.Uint64Kind: "varint",
587 protoreflect.Sfixed32Kind: "fixed32",
588 protoreflect.Fixed32Kind: "fixed32",
589 protoreflect.FloatKind: "fixed32",
590 protoreflect.Sfixed64Kind: "fixed64",
591 protoreflect.Fixed64Kind: "fixed64",
592 protoreflect.DoubleKind: "fixed64",
593 protoreflect.StringKind: "bytes",
594 protoreflect.BytesKind: "bytes",
595 protoreflect.MessageKind: "bytes",
596 protoreflect.GroupKind: "group",
597}
598
599func fieldJSONTag(field *protogen.Field) string {
600 return string(field.Desc.Name()) + ",omitempty"
601}
602
Damien Neilce36f8d2018-09-13 15:19:08 -0700603// genInitFunction generates an init function that registers the types in the
604// generated file with the proto package.
605func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
606 if len(f.allMessages) == 0 && len(f.allEnums) == 0 {
607 return
608 }
609
610 g.P("func init() {")
611 for _, message := range f.allMessages {
612 if message.Desc.IsMapEntry() {
613 continue
614 }
615
616 name := message.GoIdent.GoName
617 g.P(protogen.GoIdent{
618 GoImportPath: protoPackage,
619 GoName: "RegisterType",
620 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
621
622 // Types of map fields, sorted by the name of the field message type.
623 var mapFields []*protogen.Field
624 for _, field := range message.Fields {
625 if field.Desc.IsMap() {
626 mapFields = append(mapFields, field)
627 }
628 }
629 sort.Slice(mapFields, func(i, j int) bool {
630 ni := mapFields[i].MessageType.Desc.FullName()
631 nj := mapFields[j].MessageType.Desc.FullName()
632 return ni < nj
633 })
634 for _, field := range mapFields {
635 typeName := string(field.MessageType.Desc.FullName())
636 goType, _ := fieldGoType(g, field)
637 g.P(protogen.GoIdent{
638 GoImportPath: protoPackage,
639 GoName: "RegisterMapType",
640 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
641 }
642 }
643 for _, enum := range f.allEnums {
644 name := enum.GoIdent.GoName
645 g.P(protogen.GoIdent{
646 GoImportPath: protoPackage,
647 GoName: "RegisterEnum",
648 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
649 }
650 g.P("}")
651 g.P()
652}
653
Damien Neilcab8dfe2018-09-06 14:51:28 -0700654func genComment(g *protogen.GeneratedFile, f *File, path []int32) {
655 for _, loc := range f.locationMap[pathKey(path)] {
656 if loc.LeadingComments == nil {
657 continue
658 }
659 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
660 g.P("//", line)
661 }
662 return
663 }
664}
665
666// pathKey converts a location path to a string suitable for use as a map key.
667func pathKey(path []int32) string {
668 var buf []byte
669 for i, x := range path {
670 if i != 0 {
671 buf = append(buf, ',')
672 }
673 buf = strconv.AppendInt(buf, int64(x), 10)
674 }
675 return string(buf)
676}
Damien Neil46abb572018-09-07 12:45:37 -0700677
678func genWellKnownType(g *protogen.GeneratedFile, ident protogen.GoIdent, desc protoreflect.Descriptor) {
679 if wellKnownTypes[desc.FullName()] {
680 g.P("func (", ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
681 g.P()
682 }
683}
684
685// Names of messages and enums for which we will generate XXX_WellKnownType methods.
686var wellKnownTypes = map[protoreflect.FullName]bool{
687 "google.protobuf.NullValue": true,
688}