blob: 0c1b1192106220bcae56bf630bc8861a76852bc7 [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 Neilce36f8d2018-09-13 15:19:08 -070077 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -070078 walkMessage(message, func(message *protogen.Message) {
79 f.allMessages = append(f.allMessages, message)
80 f.allEnums = append(f.allEnums, message.Enums...)
81 f.allExtensions = append(f.allExtensions, message.Extensions...)
82 })
Damien Neilce36f8d2018-09-13 15:19:08 -070083 }
Damien Neil993c04d2018-09-14 15:41:11 -070084 f.allExtensions = append(f.allExtensions, f.File.Extensions...)
Damien Neilce36f8d2018-09-13 15:19:08 -070085
Damien Neil46abb572018-09-07 12:45:37 -070086 // Determine the name of the var holding the file descriptor:
87 //
88 // fileDescriptor_<hash of filename>
89 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
90 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
91
Damien Neil082ce922018-09-06 10:23:53 -070092 g := gen.NewGeneratedFile(f.GeneratedFilenamePrefix+".pb.go", f.GoImportPath)
Damien Neil220c2022018-08-15 11:24:18 -070093 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neilabc6fc12018-08-23 14:39:30 -070094 g.P("// source: ", f.Desc.Path())
Damien Neil220c2022018-08-15 11:24:18 -070095 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070096 const filePackageField = 2 // FileDescriptorProto.package
97 genComment(g, f, []int32{filePackageField})
98 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070099 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700100 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700101
102 // These references are not necessary, since we automatically add
103 // all necessary imports before formatting the generated file.
104 //
105 // This section exists to generate output more consistent with
106 // the previous version of protoc-gen-go, to make it easier to
107 // detect unintended variations.
108 //
109 // TODO: Eventually remove this.
110 g.P("// Reference imports to suppress errors if they are not otherwise used.")
111 g.P("var _ = ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "Marshal"})
112 g.P("var _ = ", protogen.GoIdent{GoImportPath: "fmt", GoName: "Errorf"})
113 g.P("var _ = ", protogen.GoIdent{GoImportPath: "math", GoName: "Inf"})
114 g.P()
115
Damien Neild4127922018-09-12 11:13:49 -0700116 g.P("// This is a compile-time assertion to ensure that this generated file")
117 g.P("// is compatible with the proto package it is being compiled against.")
118 g.P("// A compilation error at this line likely means your copy of the")
119 g.P("// proto package needs to be updated.")
120 g.P("const _ = ", protogen.GoIdent{
121 GoImportPath: protoPackage,
122 GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion),
123 }, "// please upgrade the proto package")
124 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700125
Damien Neilce36f8d2018-09-13 15:19:08 -0700126 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700127 genEnum(gen, g, f, enum)
128 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700129 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700130 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700131 }
Damien Neil993c04d2018-09-14 15:41:11 -0700132 for _, extension := range f.Extensions {
133 genExtension(gen, g, f, extension)
134 }
Damien Neil220c2022018-08-15 11:24:18 -0700135
Damien Neilce36f8d2018-09-13 15:19:08 -0700136 genInitFunction(gen, g, f)
Damien Neil46abb572018-09-07 12:45:37 -0700137
Damien Neil7779e052018-09-07 14:14:06 -0700138 genFileDescriptor(gen, g, f)
139}
140
Damien Neil993c04d2018-09-14 15:41:11 -0700141// walkMessage calls f on message and all of its descendants.
142func walkMessage(message *protogen.Message, f func(*protogen.Message)) {
143 f(message)
Damien Neilce36f8d2018-09-13 15:19:08 -0700144 for _, m := range message.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700145 walkMessage(m, f)
Damien Neilce36f8d2018-09-13 15:19:08 -0700146 }
147}
148
Damien Neilcab8dfe2018-09-06 14:51:28 -0700149func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil7779e052018-09-07 14:14:06 -0700150 // Trim the source_code_info from the descriptor.
151 // Marshal and gzip it.
152 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
153 descProto.SourceCodeInfo = nil
154 b, err := proto.Marshal(descProto)
155 if err != nil {
156 gen.Error(err)
157 return
158 }
159 var buf bytes.Buffer
160 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
161 w.Write(b)
162 w.Close()
163 b = buf.Bytes()
164
Damien Neil46abb572018-09-07 12:45:37 -0700165 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700166 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700167 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700168 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
169 for len(b) > 0 {
170 n := 16
171 if n > len(b) {
172 n = len(b)
173 }
174
175 s := ""
176 for _, c := range b[:n] {
177 s += fmt.Sprintf("0x%02x,", c)
178 }
179 g.P(s)
180
181 b = b[n:]
182 }
183 g.P("}")
184 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700185}
Damien Neilc7d07d92018-08-22 13:46:02 -0700186
Damien Neil46abb572018-09-07 12:45:37 -0700187func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, enum *protogen.Enum) {
188 genComment(g, f, enum.Path)
189 // TODO: deprecation
190 g.P("type ", enum.GoIdent, " int32")
191 g.P("const (")
192 for _, value := range enum.Values {
193 genComment(g, f, value.Path)
194 // TODO: deprecation
195 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number())
196 }
197 g.P(")")
198 g.P()
199 nameMap := enum.GoIdent.GoName + "_name"
200 g.P("var ", nameMap, " = map[int32]string{")
201 generated := make(map[protoreflect.EnumNumber]bool)
202 for _, value := range enum.Values {
203 duplicate := ""
204 if _, present := generated[value.Desc.Number()]; present {
205 duplicate = "// Duplicate value: "
206 }
207 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
208 generated[value.Desc.Number()] = true
209 }
210 g.P("}")
211 g.P()
212 valueMap := enum.GoIdent.GoName + "_value"
213 g.P("var ", valueMap, " = map[string]int32{")
214 for _, value := range enum.Values {
215 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
216 }
217 g.P("}")
218 g.P()
219 if enum.Desc.Syntax() != protoreflect.Proto3 {
220 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
221 g.P("p := new(", enum.GoIdent, ")")
222 g.P("*p = x")
223 g.P("return p")
224 g.P("}")
225 g.P()
226 }
227 g.P("func (x ", enum.GoIdent, ") String() string {")
228 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
229 g.P("}")
230 g.P()
231
232 if enum.Desc.Syntax() != protoreflect.Proto3 {
233 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
234 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
235 g.P("if err != nil {")
236 g.P("return err")
237 g.P("}")
238 g.P("*x = ", enum.GoIdent, "(value)")
239 g.P("return nil")
240 g.P("}")
241 g.P()
242 }
243
244 var indexes []string
245 for i := 1; i < len(enum.Path); i += 2 {
246 indexes = append(indexes, strconv.Itoa(int(enum.Path[i])))
247 }
248 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
249 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
250 g.P("}")
251 g.P()
252
253 genWellKnownType(g, enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700254}
255
Damien Neil658051b2018-09-10 12:26:21 -0700256// enumRegistryName returns the name used to register an enum with the proto
257// package registry.
258//
259// Confusingly, this is <proto_package>.<go_ident>. This probably should have
260// been the full name of the proto enum type instead, but changing it at this
261// point would require thought.
262func enumRegistryName(enum *protogen.Enum) string {
263 // Find the FileDescriptor for this enum.
264 var desc protoreflect.Descriptor = enum.Desc
265 for {
266 p, ok := desc.Parent()
267 if !ok {
268 break
269 }
270 desc = p
271 }
272 fdesc := desc.(protoreflect.FileDescriptor)
273 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
274}
275
Damien Neilcab8dfe2018-09-06 14:51:28 -0700276func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700277 if message.Desc.IsMapEntry() {
278 return
279 }
280
Damien Neilcab8dfe2018-09-06 14:51:28 -0700281 genComment(g, f, message.Path)
Damien Neil658051b2018-09-10 12:26:21 -0700282 // TODO: deprecation
Damien Neilcab8dfe2018-09-06 14:51:28 -0700283 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700284 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700285 if field.OneofType != nil {
286 // It would be a bit simpler to iterate over the oneofs below,
287 // but generating the field here keeps the contents of the Go
288 // struct in the same order as the contents of the source
289 // .proto file.
290 if field == field.OneofType.Fields[0] {
291 genOneofField(gen, g, f, message, field.OneofType)
292 }
Damien Neil658051b2018-09-10 12:26:21 -0700293 continue
294 }
295 genComment(g, f, field.Path)
Damien Neil77f82fe2018-09-13 10:59:17 -0700296 goType, pointer := fieldGoType(g, field)
297 if pointer {
298 goType = "*" + goType
299 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700300 tags := []string{
301 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
302 fmt.Sprintf("json:%q", fieldJSONTag(field)),
303 }
304 if field.Desc.IsMap() {
305 key := field.MessageType.Fields[0]
306 val := field.MessageType.Fields[1]
307 tags = append(tags,
308 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
309 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
310 )
311 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700312 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
Damien Neil658051b2018-09-10 12:26:21 -0700313 }
314 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700315
316 if message.Desc.ExtensionRanges().Len() > 0 {
317 var tags []string
318 if messageOptions(gen, message).GetMessageSetWireFormat() {
319 tags = append(tags, `protobuf_messageset:"1"`)
320 }
321 tags = append(tags, `json:"-"`)
322 g.P(protogen.GoIdent{
323 GoImportPath: protoPackage,
324 GoName: "XXX_InternalExtensions",
325 }, " `", strings.Join(tags, " "), "`")
326 }
Damien Neil658051b2018-09-10 12:26:21 -0700327 // TODO XXX_InternalExtensions
328 g.P("XXX_unrecognized []byte `json:\"-\"`")
329 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700330 g.P("}")
331 g.P()
332
Damien Neila1c6abc2018-09-12 13:36:34 -0700333 // Reset
334 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
335 // String
336 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
337 GoImportPath: protoPackage,
338 GoName: "CompactTextString",
339 }, "(m) }")
340 // ProtoMessage
341 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
342 // Descriptor
343 var indexes []string
344 for i := 1; i < len(message.Path); i += 2 {
345 indexes = append(indexes, strconv.Itoa(int(message.Path[i])))
346 }
347 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
348 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
349 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700350 g.P()
351
352 // ExtensionRangeArray
353 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
354 if messageOptions(gen, message).GetMessageSetWireFormat() {
355 g.P("func (m *", message.GoIdent, ") MarshalJSON() ([]byte, error) {")
356 g.P("return ", protogen.GoIdent{
357 GoImportPath: protoPackage,
358 GoName: "MarshalMessageSetJSON",
359 }, "(&m.XXX_InternalExtensions)")
360 g.P("}")
361 g.P("func (m *", message.GoIdent, ") UnmarshalJSON(buf []byte) error {")
362 g.P("return ", protogen.GoIdent{
363 GoImportPath: protoPackage,
364 GoName: "UnmarshalMessageSetJSON",
365 }, "(buf, &m.XXX_InternalExtensions)")
366 g.P("}")
367 g.P()
368 }
369
370 protoExtRange := protogen.GoIdent{
371 GoImportPath: protoPackage,
372 GoName: "ExtensionRange",
373 }
374 extRangeVar := "extRange_" + message.GoIdent.GoName
375 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
376 for i := 0; i < extranges.Len(); i++ {
377 r := extranges.Get(i)
378 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
379 }
380 g.P("}")
381 g.P()
382 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
383 g.P("return ", extRangeVar)
384 g.P("}")
385 g.P()
386 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700387
388 // Table-driven proto support.
389 //
390 // TODO: It does not scale to keep adding another method for every
391 // operation on protos that we want to switch over to using the
392 // table-driven approach. Instead, we should only add a single method
393 // that allows getting access to the *InternalMessageInfo struct and then
394 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
395 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
396 // XXX_Unmarshal
397 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
398 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
399 g.P("}")
400 // XXX_Marshal
401 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
402 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
403 g.P("}")
404 // XXX_Merge
405 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
406 g.P(messageInfoVar, ".Merge(m, src)")
407 g.P("}")
408 // XXX_Size
409 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
410 g.P("return ", messageInfoVar, ".Size(m)")
411 g.P("}")
412 // XXX_DiscardUnknown
413 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
414 g.P(messageInfoVar, ".DiscardUnknown(m)")
415 g.P("}")
416 g.P()
417 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
418 GoImportPath: protoPackage,
419 GoName: "InternalMessageInfo",
420 })
421 g.P()
422
Damien Neilebc699d2018-09-13 08:50:13 -0700423 // Constants and vars holding the default values of fields.
424 for _, field := range message.Fields {
425 if !field.Desc.HasDefault() {
426 continue
427 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700428 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700429 def := field.Desc.Default()
430 switch field.Desc.Kind() {
431 case protoreflect.StringKind:
432 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
433 case protoreflect.BytesKind:
434 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
435 case protoreflect.EnumKind:
436 enum := field.EnumType
437 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
438 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
439 case protoreflect.FloatKind, protoreflect.DoubleKind:
440 // Floating point numbers need extra handling for -Inf/Inf/NaN.
441 f := field.Desc.Default().Float()
442 goType := "float64"
443 if field.Desc.Kind() == protoreflect.FloatKind {
444 goType = "float32"
445 }
446 // funcCall returns a call to a function in the math package,
447 // possibly converting the result to float32.
448 funcCall := func(fn, param string) string {
449 s := g.QualifiedGoIdent(protogen.GoIdent{
450 GoImportPath: "math",
451 GoName: fn,
452 }) + param
453 if goType != "float64" {
454 s = goType + "(" + s + ")"
455 }
456 return s
457 }
458 switch {
459 case math.IsInf(f, -1):
460 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
461 case math.IsInf(f, 1):
462 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
463 case math.IsNaN(f):
464 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
465 default:
466 g.P("const ", defVarName, " ", goType, " = ", f)
467 }
468 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700469 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700470 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
471 }
472 }
473 g.P()
474
Damien Neil77f82fe2018-09-13 10:59:17 -0700475 // Getters.
476 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700477 if field.OneofType != nil {
478 if field == field.OneofType.Fields[0] {
479 genOneofTypes(gen, g, f, message, field.OneofType)
480 }
481 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700482 goType, pointer := fieldGoType(g, field)
483 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil1fa78d82018-09-13 13:12:36 -0700484 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
485 if field.OneofType != nil {
486 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", message.GoIdent.GoName, "_", field.GoName, "); ok {")
487 g.P("return x.", field.GoName)
488 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700489 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700490 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
491 g.P("if m != nil {")
492 } else {
493 g.P("if m != nil && m.", field.GoName, " != nil {")
494 }
495 star := ""
496 if pointer {
497 star = "*"
498 }
499 g.P("return ", star, " m.", field.GoName)
500 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700501 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700502 g.P("return ", defaultValue)
503 g.P("}")
504 g.P()
505 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700506
Damien Neilce36f8d2018-09-13 15:19:08 -0700507 genWellKnownType(g, message.GoIdent, message.Desc)
Damien Neil1fa78d82018-09-13 13:12:36 -0700508
509 if len(message.Oneofs) > 0 {
510 genOneofFuncs(gen, g, f, message)
511 }
Damien Neil993c04d2018-09-14 15:41:11 -0700512 for _, extension := range message.Extensions {
513 genExtension(gen, g, f, extension)
514 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700515}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700516
Damien Neil77f82fe2018-09-13 10:59:17 -0700517// fieldGoType returns the Go type used for a field.
518//
519// If it returns pointer=true, the struct field is a pointer to the type.
520func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700521 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700522 switch field.Desc.Kind() {
523 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700524 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700525 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700526 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700527 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700528 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700529 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700530 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700531 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700532 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700533 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700534 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700535 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700536 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700537 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700538 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700539 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700540 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700541 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700542 goType = "[]byte"
543 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700544 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700545 if field.Desc.IsMap() {
546 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
547 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
548 return fmt.Sprintf("map[%v]%v", keyType, valType), false
549 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700550 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
551 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700552 }
553 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700554 goType = "[]" + goType
555 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700556 }
557 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700558 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700559 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700560 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700561}
562
563func fieldProtobufTag(field *protogen.Field) string {
564 var tag []string
565 // wire type
566 tag = append(tag, wireTypes[field.Desc.Kind()])
567 // field number
568 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
569 // cardinality
570 switch field.Desc.Cardinality() {
571 case protoreflect.Optional:
572 tag = append(tag, "opt")
573 case protoreflect.Required:
574 tag = append(tag, "req")
575 case protoreflect.Repeated:
576 tag = append(tag, "rep")
577 }
Damien Neil658051b2018-09-10 12:26:21 -0700578 // TODO: packed
579 // name
580 name := string(field.Desc.Name())
581 if field.Desc.Kind() == protoreflect.GroupKind {
582 // The name of the FieldDescriptor for a group field is
583 // lowercased. To find the original capitalization, we
584 // look in the field's MessageType.
585 name = string(field.MessageType.Desc.Name())
586 }
587 tag = append(tag, "name="+name)
588 // JSON name
589 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
590 tag = append(tag, "json="+jsonName)
591 }
592 // proto3
593 if field.Desc.Syntax() == protoreflect.Proto3 {
594 tag = append(tag, "proto3")
595 }
596 // enum
597 if field.Desc.Kind() == protoreflect.EnumKind {
598 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
599 }
600 // oneof
601 if field.Desc.OneofType() != nil {
602 tag = append(tag, "oneof")
603 }
Damien Neilebc699d2018-09-13 08:50:13 -0700604 // default value
605 // This must appear last in the tag, since commas in strings aren't escaped.
606 if field.Desc.HasDefault() {
607 var def string
608 switch field.Desc.Kind() {
609 case protoreflect.BoolKind:
610 if field.Desc.Default().Bool() {
611 def = "1"
612 } else {
613 def = "0"
614 }
615 case protoreflect.BytesKind:
616 def = string(field.Desc.Default().Bytes())
617 case protoreflect.FloatKind, protoreflect.DoubleKind:
618 f := field.Desc.Default().Float()
619 switch {
620 case math.IsInf(f, -1):
621 def = "-inf"
622 case math.IsInf(f, 1):
623 def = "inf"
624 case math.IsNaN(f):
625 def = "nan"
626 default:
627 def = fmt.Sprint(f)
628 }
629 default:
630 def = fmt.Sprint(field.Desc.Default().Interface())
631 }
632 tag = append(tag, "def="+def)
633 }
Damien Neil658051b2018-09-10 12:26:21 -0700634 return strings.Join(tag, ",")
635}
636
Damien Neil77f82fe2018-09-13 10:59:17 -0700637func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
638 if field.Desc.Cardinality() == protoreflect.Repeated {
639 return "nil"
640 }
641 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700642 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700643 if field.Desc.Kind() == protoreflect.BytesKind {
644 return "append([]byte(nil), " + defVarName + "...)"
645 }
646 return defVarName
647 }
648 switch field.Desc.Kind() {
649 case protoreflect.BoolKind:
650 return "false"
651 case protoreflect.StringKind:
652 return `""`
653 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
654 return "nil"
655 case protoreflect.EnumKind:
656 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
657 default:
658 return "0"
659 }
660}
661
Damien Neil658051b2018-09-10 12:26:21 -0700662var wireTypes = map[protoreflect.Kind]string{
663 protoreflect.BoolKind: "varint",
664 protoreflect.EnumKind: "varint",
665 protoreflect.Int32Kind: "varint",
666 protoreflect.Sint32Kind: "zigzag32",
667 protoreflect.Uint32Kind: "varint",
668 protoreflect.Int64Kind: "varint",
669 protoreflect.Sint64Kind: "zigzag64",
670 protoreflect.Uint64Kind: "varint",
671 protoreflect.Sfixed32Kind: "fixed32",
672 protoreflect.Fixed32Kind: "fixed32",
673 protoreflect.FloatKind: "fixed32",
674 protoreflect.Sfixed64Kind: "fixed64",
675 protoreflect.Fixed64Kind: "fixed64",
676 protoreflect.DoubleKind: "fixed64",
677 protoreflect.StringKind: "bytes",
678 protoreflect.BytesKind: "bytes",
679 protoreflect.MessageKind: "bytes",
680 protoreflect.GroupKind: "group",
681}
682
683func fieldJSONTag(field *protogen.Field) string {
684 return string(field.Desc.Name()) + ",omitempty"
685}
686
Damien Neil993c04d2018-09-14 15:41:11 -0700687func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, extension *protogen.Extension) {
688 g.P("var ", extensionVar(f, extension), " = &", protogen.GoIdent{
689 GoImportPath: protoPackage,
690 GoName: "ExtensionDesc",
691 }, "{")
692 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
693 goType, pointer := fieldGoType(g, extension)
694 if pointer {
695 goType = "*" + goType
696 }
697 g.P("ExtensionType: (", goType, ")(nil),")
698 g.P("Field: ", extension.Desc.Number(), ",")
699 g.P("Name: ", strconv.Quote(string(extension.Desc.FullName())), ",")
700 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
701 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
702 g.P("}")
703 g.P()
704}
705
706// extensionVar returns the var holding the ExtensionDesc for an extension.
707func extensionVar(f *File, extension *protogen.Extension) protogen.GoIdent {
708 name := "E_"
709 if extension.ParentMessage != nil {
710 name += extension.ParentMessage.GoIdent.GoName + "_"
711 }
712 name += extension.GoName
713 return protogen.GoIdent{
714 GoImportPath: f.GoImportPath,
715 GoName: name,
716 }
717}
718
Damien Neilce36f8d2018-09-13 15:19:08 -0700719// genInitFunction generates an init function that registers the types in the
720// generated file with the proto package.
721func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil993c04d2018-09-14 15:41:11 -0700722 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700723 return
724 }
725
726 g.P("func init() {")
727 for _, message := range f.allMessages {
728 if message.Desc.IsMapEntry() {
729 continue
730 }
731
732 name := message.GoIdent.GoName
733 g.P(protogen.GoIdent{
734 GoImportPath: protoPackage,
735 GoName: "RegisterType",
736 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
737
738 // Types of map fields, sorted by the name of the field message type.
739 var mapFields []*protogen.Field
740 for _, field := range message.Fields {
741 if field.Desc.IsMap() {
742 mapFields = append(mapFields, field)
743 }
744 }
745 sort.Slice(mapFields, func(i, j int) bool {
746 ni := mapFields[i].MessageType.Desc.FullName()
747 nj := mapFields[j].MessageType.Desc.FullName()
748 return ni < nj
749 })
750 for _, field := range mapFields {
751 typeName := string(field.MessageType.Desc.FullName())
752 goType, _ := fieldGoType(g, field)
753 g.P(protogen.GoIdent{
754 GoImportPath: protoPackage,
755 GoName: "RegisterMapType",
756 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
757 }
758 }
759 for _, enum := range f.allEnums {
760 name := enum.GoIdent.GoName
761 g.P(protogen.GoIdent{
762 GoImportPath: protoPackage,
763 GoName: "RegisterEnum",
764 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
765 }
Damien Neil993c04d2018-09-14 15:41:11 -0700766 for _, extension := range f.allExtensions {
767 g.P(protogen.GoIdent{
768 GoImportPath: protoPackage,
769 GoName: "RegisterExtension",
770 }, "(", extensionVar(f, extension), ")")
771 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700772 g.P("}")
773 g.P()
774}
775
Damien Neil1fa78d82018-09-13 13:12:36 -0700776func genComment(g *protogen.GeneratedFile, f *File, path []int32) (hasComment bool) {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700777 for _, loc := range f.locationMap[pathKey(path)] {
778 if loc.LeadingComments == nil {
779 continue
780 }
781 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
Damien Neil1fa78d82018-09-13 13:12:36 -0700782 hasComment = true
Damien Neilcab8dfe2018-09-06 14:51:28 -0700783 g.P("//", line)
784 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700785 break
Damien Neilcab8dfe2018-09-06 14:51:28 -0700786 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700787 return hasComment
Damien Neilcab8dfe2018-09-06 14:51:28 -0700788}
789
790// pathKey converts a location path to a string suitable for use as a map key.
791func pathKey(path []int32) string {
792 var buf []byte
793 for i, x := range path {
794 if i != 0 {
795 buf = append(buf, ',')
796 }
797 buf = strconv.AppendInt(buf, int64(x), 10)
798 }
799 return string(buf)
800}
Damien Neil46abb572018-09-07 12:45:37 -0700801
802func genWellKnownType(g *protogen.GeneratedFile, ident protogen.GoIdent, desc protoreflect.Descriptor) {
803 if wellKnownTypes[desc.FullName()] {
804 g.P("func (", ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
805 g.P()
806 }
807}
808
809// Names of messages and enums for which we will generate XXX_WellKnownType methods.
810var wellKnownTypes = map[protoreflect.FullName]bool{
811 "google.protobuf.NullValue": true,
812}