blob: c7d9f8d49da842132b11a611ac72def844f0f636 [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 Neild4127922018-09-12 11:13:49 -070092 g.P("// This is a compile-time assertion to ensure that this generated file")
93 g.P("// is compatible with the proto package it is being compiled against.")
94 g.P("// A compilation error at this line likely means your copy of the")
95 g.P("// proto package needs to be updated.")
96 g.P("const _ = ", protogen.GoIdent{
97 GoImportPath: protoPackage,
98 GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion),
99 }, "// please upgrade the proto package")
100 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700101
Damien Neilce36f8d2018-09-13 15:19:08 -0700102 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700103 genEnum(gen, g, f, enum)
104 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700105 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700106 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700107 }
Damien Neil220c2022018-08-15 11:24:18 -0700108
Damien Neilce36f8d2018-09-13 15:19:08 -0700109 genInitFunction(gen, g, f)
Damien Neil46abb572018-09-07 12:45:37 -0700110
Damien Neil7779e052018-09-07 14:14:06 -0700111 genFileDescriptor(gen, g, f)
112}
113
Damien Neilce36f8d2018-09-13 15:19:08 -0700114func (f *File) initMessage(message *protogen.Message) {
115 f.allEnums = append(f.allEnums, message.Enums...)
116 f.allMessages = append(f.allMessages, message.Messages...)
117 for _, m := range message.Messages {
118 f.initMessage(m)
119 }
120}
121
Damien Neilcab8dfe2018-09-06 14:51:28 -0700122func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
Damien Neil7779e052018-09-07 14:14:06 -0700123 // Trim the source_code_info from the descriptor.
124 // Marshal and gzip it.
125 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
126 descProto.SourceCodeInfo = nil
127 b, err := proto.Marshal(descProto)
128 if err != nil {
129 gen.Error(err)
130 return
131 }
132 var buf bytes.Buffer
133 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
134 w.Write(b)
135 w.Close()
136 b = buf.Bytes()
137
Damien Neil46abb572018-09-07 12:45:37 -0700138 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700139 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700140 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700141 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
142 for len(b) > 0 {
143 n := 16
144 if n > len(b) {
145 n = len(b)
146 }
147
148 s := ""
149 for _, c := range b[:n] {
150 s += fmt.Sprintf("0x%02x,", c)
151 }
152 g.P(s)
153
154 b = b[n:]
155 }
156 g.P("}")
157 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700158}
Damien Neilc7d07d92018-08-22 13:46:02 -0700159
Damien Neil46abb572018-09-07 12:45:37 -0700160func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, enum *protogen.Enum) {
161 genComment(g, f, enum.Path)
162 // TODO: deprecation
163 g.P("type ", enum.GoIdent, " int32")
164 g.P("const (")
165 for _, value := range enum.Values {
166 genComment(g, f, value.Path)
167 // TODO: deprecation
168 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number())
169 }
170 g.P(")")
171 g.P()
172 nameMap := enum.GoIdent.GoName + "_name"
173 g.P("var ", nameMap, " = map[int32]string{")
174 generated := make(map[protoreflect.EnumNumber]bool)
175 for _, value := range enum.Values {
176 duplicate := ""
177 if _, present := generated[value.Desc.Number()]; present {
178 duplicate = "// Duplicate value: "
179 }
180 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
181 generated[value.Desc.Number()] = true
182 }
183 g.P("}")
184 g.P()
185 valueMap := enum.GoIdent.GoName + "_value"
186 g.P("var ", valueMap, " = map[string]int32{")
187 for _, value := range enum.Values {
188 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
189 }
190 g.P("}")
191 g.P()
192 if enum.Desc.Syntax() != protoreflect.Proto3 {
193 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
194 g.P("p := new(", enum.GoIdent, ")")
195 g.P("*p = x")
196 g.P("return p")
197 g.P("}")
198 g.P()
199 }
200 g.P("func (x ", enum.GoIdent, ") String() string {")
201 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
202 g.P("}")
203 g.P()
204
205 if enum.Desc.Syntax() != protoreflect.Proto3 {
206 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
207 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
208 g.P("if err != nil {")
209 g.P("return err")
210 g.P("}")
211 g.P("*x = ", enum.GoIdent, "(value)")
212 g.P("return nil")
213 g.P("}")
214 g.P()
215 }
216
217 var indexes []string
218 for i := 1; i < len(enum.Path); i += 2 {
219 indexes = append(indexes, strconv.Itoa(int(enum.Path[i])))
220 }
221 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
222 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
223 g.P("}")
224 g.P()
225
226 genWellKnownType(g, enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700227}
228
Damien Neil658051b2018-09-10 12:26:21 -0700229// enumRegistryName returns the name used to register an enum with the proto
230// package registry.
231//
232// Confusingly, this is <proto_package>.<go_ident>. This probably should have
233// been the full name of the proto enum type instead, but changing it at this
234// point would require thought.
235func enumRegistryName(enum *protogen.Enum) string {
236 // Find the FileDescriptor for this enum.
237 var desc protoreflect.Descriptor = enum.Desc
238 for {
239 p, ok := desc.Parent()
240 if !ok {
241 break
242 }
243 desc = p
244 }
245 fdesc := desc.(protoreflect.FileDescriptor)
246 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
247}
248
Damien Neilcab8dfe2018-09-06 14:51:28 -0700249func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700250 if message.Desc.IsMapEntry() {
251 return
252 }
253
Damien Neilcab8dfe2018-09-06 14:51:28 -0700254 genComment(g, f, message.Path)
Damien Neil658051b2018-09-10 12:26:21 -0700255 // TODO: deprecation
Damien Neilcab8dfe2018-09-06 14:51:28 -0700256 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700257 for _, field := range message.Fields {
258 if field.Desc.OneofType() != nil {
259 // TODO oneofs
260 continue
261 }
262 genComment(g, f, field.Path)
Damien Neil77f82fe2018-09-13 10:59:17 -0700263 goType, pointer := fieldGoType(g, field)
264 if pointer {
265 goType = "*" + goType
266 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700267 tags := []string{
268 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
269 fmt.Sprintf("json:%q", fieldJSONTag(field)),
270 }
271 if field.Desc.IsMap() {
272 key := field.MessageType.Fields[0]
273 val := field.MessageType.Fields[1]
274 tags = append(tags,
275 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
276 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
277 )
278 }
279 g.P(field.GoIdent, " ", goType, " `", strings.Join(tags, " "), "`")
Damien Neil658051b2018-09-10 12:26:21 -0700280 }
281 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
282 // TODO XXX_InternalExtensions
283 g.P("XXX_unrecognized []byte `json:\"-\"`")
284 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700285 g.P("}")
286 g.P()
287
Damien Neila1c6abc2018-09-12 13:36:34 -0700288 // Reset
289 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
290 // String
291 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
292 GoImportPath: protoPackage,
293 GoName: "CompactTextString",
294 }, "(m) }")
295 // ProtoMessage
296 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
297 // Descriptor
298 var indexes []string
299 for i := 1; i < len(message.Path); i += 2 {
300 indexes = append(indexes, strconv.Itoa(int(message.Path[i])))
301 }
302 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
303 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
304 g.P("}")
305 // TODO: extension support methods
306
307 // Table-driven proto support.
308 //
309 // TODO: It does not scale to keep adding another method for every
310 // operation on protos that we want to switch over to using the
311 // table-driven approach. Instead, we should only add a single method
312 // that allows getting access to the *InternalMessageInfo struct and then
313 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
314 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
315 // XXX_Unmarshal
316 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
317 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
318 g.P("}")
319 // XXX_Marshal
320 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
321 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
322 g.P("}")
323 // XXX_Merge
324 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
325 g.P(messageInfoVar, ".Merge(m, src)")
326 g.P("}")
327 // XXX_Size
328 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
329 g.P("return ", messageInfoVar, ".Size(m)")
330 g.P("}")
331 // XXX_DiscardUnknown
332 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
333 g.P(messageInfoVar, ".DiscardUnknown(m)")
334 g.P("}")
335 g.P()
336 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
337 GoImportPath: protoPackage,
338 GoName: "InternalMessageInfo",
339 })
340 g.P()
341
Damien Neilebc699d2018-09-13 08:50:13 -0700342 // Constants and vars holding the default values of fields.
343 for _, field := range message.Fields {
344 if !field.Desc.HasDefault() {
345 continue
346 }
347 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoIdent.GoName
348 def := field.Desc.Default()
349 switch field.Desc.Kind() {
350 case protoreflect.StringKind:
351 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
352 case protoreflect.BytesKind:
353 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
354 case protoreflect.EnumKind:
355 enum := field.EnumType
356 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
357 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
358 case protoreflect.FloatKind, protoreflect.DoubleKind:
359 // Floating point numbers need extra handling for -Inf/Inf/NaN.
360 f := field.Desc.Default().Float()
361 goType := "float64"
362 if field.Desc.Kind() == protoreflect.FloatKind {
363 goType = "float32"
364 }
365 // funcCall returns a call to a function in the math package,
366 // possibly converting the result to float32.
367 funcCall := func(fn, param string) string {
368 s := g.QualifiedGoIdent(protogen.GoIdent{
369 GoImportPath: "math",
370 GoName: fn,
371 }) + param
372 if goType != "float64" {
373 s = goType + "(" + s + ")"
374 }
375 return s
376 }
377 switch {
378 case math.IsInf(f, -1):
379 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
380 case math.IsInf(f, 1):
381 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
382 case math.IsNaN(f):
383 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
384 default:
385 g.P("const ", defVarName, " ", goType, " = ", f)
386 }
387 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700388 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700389 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
390 }
391 }
392 g.P()
393
Damien Neil77f82fe2018-09-13 10:59:17 -0700394 // Getters.
395 for _, field := range message.Fields {
396 goType, pointer := fieldGoType(g, field)
397 defaultValue := fieldDefaultValue(g, message, field)
398 g.P("func (m *", message.GoIdent, ") Get", field.GoIdent, "() ", goType, " {")
399 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
400 g.P("if m != nil {")
401 } else {
402 g.P("if m != nil && m.", field.GoIdent, " != nil {")
403 }
404 star := ""
405 if pointer {
406 star = "*"
407 }
408 g.P("return ", star, " m.", field.GoIdent)
409 g.P("}")
410 g.P("return ", defaultValue)
411 g.P("}")
412 g.P()
413 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700414
Damien Neilce36f8d2018-09-13 15:19:08 -0700415 genWellKnownType(g, message.GoIdent, message.Desc)
Damien Neilc7d07d92018-08-22 13:46:02 -0700416}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700417
Damien Neil77f82fe2018-09-13 10:59:17 -0700418// fieldGoType returns the Go type used for a field.
419//
420// If it returns pointer=true, the struct field is a pointer to the type.
421func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700422 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700423 switch field.Desc.Kind() {
424 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700425 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700426 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700427 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700428 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700429 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700430 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700431 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700432 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700433 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700434 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700435 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700436 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700437 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700438 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700439 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700440 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700441 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700442 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700443 goType = "[]byte"
444 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700445 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700446 if field.Desc.IsMap() {
447 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
448 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
449 return fmt.Sprintf("map[%v]%v", keyType, valType), false
450 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700451 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
452 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700453 }
454 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700455 goType = "[]" + goType
456 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700457 }
458 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700459 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700460 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700461 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700462}
463
464func fieldProtobufTag(field *protogen.Field) string {
465 var tag []string
466 // wire type
467 tag = append(tag, wireTypes[field.Desc.Kind()])
468 // field number
469 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
470 // cardinality
471 switch field.Desc.Cardinality() {
472 case protoreflect.Optional:
473 tag = append(tag, "opt")
474 case protoreflect.Required:
475 tag = append(tag, "req")
476 case protoreflect.Repeated:
477 tag = append(tag, "rep")
478 }
Damien Neil658051b2018-09-10 12:26:21 -0700479 // TODO: packed
480 // name
481 name := string(field.Desc.Name())
482 if field.Desc.Kind() == protoreflect.GroupKind {
483 // The name of the FieldDescriptor for a group field is
484 // lowercased. To find the original capitalization, we
485 // look in the field's MessageType.
486 name = string(field.MessageType.Desc.Name())
487 }
488 tag = append(tag, "name="+name)
489 // JSON name
490 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
491 tag = append(tag, "json="+jsonName)
492 }
493 // proto3
494 if field.Desc.Syntax() == protoreflect.Proto3 {
495 tag = append(tag, "proto3")
496 }
497 // enum
498 if field.Desc.Kind() == protoreflect.EnumKind {
499 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
500 }
501 // oneof
502 if field.Desc.OneofType() != nil {
503 tag = append(tag, "oneof")
504 }
Damien Neilebc699d2018-09-13 08:50:13 -0700505 // default value
506 // This must appear last in the tag, since commas in strings aren't escaped.
507 if field.Desc.HasDefault() {
508 var def string
509 switch field.Desc.Kind() {
510 case protoreflect.BoolKind:
511 if field.Desc.Default().Bool() {
512 def = "1"
513 } else {
514 def = "0"
515 }
516 case protoreflect.BytesKind:
517 def = string(field.Desc.Default().Bytes())
518 case protoreflect.FloatKind, protoreflect.DoubleKind:
519 f := field.Desc.Default().Float()
520 switch {
521 case math.IsInf(f, -1):
522 def = "-inf"
523 case math.IsInf(f, 1):
524 def = "inf"
525 case math.IsNaN(f):
526 def = "nan"
527 default:
528 def = fmt.Sprint(f)
529 }
530 default:
531 def = fmt.Sprint(field.Desc.Default().Interface())
532 }
533 tag = append(tag, "def="+def)
534 }
Damien Neil658051b2018-09-10 12:26:21 -0700535 return strings.Join(tag, ",")
536}
537
Damien Neil77f82fe2018-09-13 10:59:17 -0700538func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
539 if field.Desc.Cardinality() == protoreflect.Repeated {
540 return "nil"
541 }
542 if field.Desc.HasDefault() {
543 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoIdent.GoName
544 if field.Desc.Kind() == protoreflect.BytesKind {
545 return "append([]byte(nil), " + defVarName + "...)"
546 }
547 return defVarName
548 }
549 switch field.Desc.Kind() {
550 case protoreflect.BoolKind:
551 return "false"
552 case protoreflect.StringKind:
553 return `""`
554 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
555 return "nil"
556 case protoreflect.EnumKind:
557 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
558 default:
559 return "0"
560 }
561}
562
Damien Neil658051b2018-09-10 12:26:21 -0700563var wireTypes = map[protoreflect.Kind]string{
564 protoreflect.BoolKind: "varint",
565 protoreflect.EnumKind: "varint",
566 protoreflect.Int32Kind: "varint",
567 protoreflect.Sint32Kind: "zigzag32",
568 protoreflect.Uint32Kind: "varint",
569 protoreflect.Int64Kind: "varint",
570 protoreflect.Sint64Kind: "zigzag64",
571 protoreflect.Uint64Kind: "varint",
572 protoreflect.Sfixed32Kind: "fixed32",
573 protoreflect.Fixed32Kind: "fixed32",
574 protoreflect.FloatKind: "fixed32",
575 protoreflect.Sfixed64Kind: "fixed64",
576 protoreflect.Fixed64Kind: "fixed64",
577 protoreflect.DoubleKind: "fixed64",
578 protoreflect.StringKind: "bytes",
579 protoreflect.BytesKind: "bytes",
580 protoreflect.MessageKind: "bytes",
581 protoreflect.GroupKind: "group",
582}
583
584func fieldJSONTag(field *protogen.Field) string {
585 return string(field.Desc.Name()) + ",omitempty"
586}
587
Damien Neilce36f8d2018-09-13 15:19:08 -0700588// genInitFunction generates an init function that registers the types in the
589// generated file with the proto package.
590func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) {
591 if len(f.allMessages) == 0 && len(f.allEnums) == 0 {
592 return
593 }
594
595 g.P("func init() {")
596 for _, message := range f.allMessages {
597 if message.Desc.IsMapEntry() {
598 continue
599 }
600
601 name := message.GoIdent.GoName
602 g.P(protogen.GoIdent{
603 GoImportPath: protoPackage,
604 GoName: "RegisterType",
605 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
606
607 // Types of map fields, sorted by the name of the field message type.
608 var mapFields []*protogen.Field
609 for _, field := range message.Fields {
610 if field.Desc.IsMap() {
611 mapFields = append(mapFields, field)
612 }
613 }
614 sort.Slice(mapFields, func(i, j int) bool {
615 ni := mapFields[i].MessageType.Desc.FullName()
616 nj := mapFields[j].MessageType.Desc.FullName()
617 return ni < nj
618 })
619 for _, field := range mapFields {
620 typeName := string(field.MessageType.Desc.FullName())
621 goType, _ := fieldGoType(g, field)
622 g.P(protogen.GoIdent{
623 GoImportPath: protoPackage,
624 GoName: "RegisterMapType",
625 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
626 }
627 }
628 for _, enum := range f.allEnums {
629 name := enum.GoIdent.GoName
630 g.P(protogen.GoIdent{
631 GoImportPath: protoPackage,
632 GoName: "RegisterEnum",
633 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
634 }
635 g.P("}")
636 g.P()
637}
638
Damien Neilcab8dfe2018-09-06 14:51:28 -0700639func genComment(g *protogen.GeneratedFile, f *File, path []int32) {
640 for _, loc := range f.locationMap[pathKey(path)] {
641 if loc.LeadingComments == nil {
642 continue
643 }
644 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
645 g.P("//", line)
646 }
647 return
648 }
649}
650
651// pathKey converts a location path to a string suitable for use as a map key.
652func pathKey(path []int32) string {
653 var buf []byte
654 for i, x := range path {
655 if i != 0 {
656 buf = append(buf, ',')
657 }
658 buf = strconv.AppendInt(buf, int64(x), 10)
659 }
660 return string(buf)
661}
Damien Neil46abb572018-09-07 12:45:37 -0700662
663func genWellKnownType(g *protogen.GeneratedFile, ident protogen.GoIdent, desc protoreflect.Descriptor) {
664 if wellKnownTypes[desc.FullName()] {
665 g.P("func (", ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
666 g.P()
667 }
668}
669
670// Names of messages and enums for which we will generate XXX_WellKnownType methods.
671var wellKnownTypes = map[protoreflect.FullName]bool{
672 "google.protobuf.NullValue": true,
673}