blob: 08a7660b5d34b14103b9bf0c92cfb5a89807ed88 [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
Damien Neil1adaec92018-09-24 13:43:03 -07005// Package internal_gengo is internal to the protobuf module.
6package internal_gengo
Damien Neil220c2022018-08-15 11:24:18 -07007
8import (
Damien Neil7779e052018-09-07 14:14:06 -07009 "bytes"
10 "compress/gzip"
11 "crypto/sha256"
12 "encoding/hex"
13 "fmt"
Damien Neilebc699d2018-09-13 08:50:13 -070014 "math"
Damien Neilce36f8d2018-09-13 15:19:08 -070015 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070016 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070017 "strings"
Damien Neil7779e052018-09-07 14:14:06 -070018
19 "github.com/golang/protobuf/proto"
Joe Tsai05828db2018-11-01 13:52:16 -070020 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai01ab2962018-09-21 17:44:00 -070021 "github.com/golang/protobuf/v2/protogen"
22 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080023
24 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
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).
Joe Tsaid7e97bc2018-11-26 12:57:27 -080031const generatedCodeVersion = 3
Damien Neild4127922018-09-12 11:13:49 -070032
Joe Tsaic1c17aa2018-11-16 11:14:14 -080033const (
Joe Tsai24ceb2b2018-12-04 22:53:56 -080034 fmtPackage = protogen.GoImportPath("fmt")
35 mathPackage = protogen.GoImportPath("math")
36 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
37 protoapiPackage = protogen.GoImportPath("github.com/golang/protobuf/protoapi")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080038)
Damien Neil46abb572018-09-07 12:45:37 -070039
Damien Neild39efc82018-09-24 12:38:10 -070040type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070041 *protogen.File
Damien Neil46abb572018-09-07 12:45:37 -070042 descriptorVar string // var containing the gzipped FileDescriptorProto
Joe Tsaib6405bd2018-11-15 14:44:37 -080043
Joe Tsai9667c482018-12-05 15:42:52 -080044 allEnums []*protogen.Enum
45 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
46 allMessages []*protogen.Message
47 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
48 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070049}
50
Joe Tsai24ceb2b2018-12-04 22:53:56 -080051// protoPackage returns the package to import, which is either the protoPackage
52// or the protoapiPackage constant.
53//
54// This special casing exists because we are unable to move InternalMessageInfo
55// to protoapi since the implementation behind that logic is heavy and
56// too intricately connected to other parts of the proto package.
57// The descriptor proto is special in that it avoids using InternalMessageInfo
58// so that it is able to depend solely on protoapi and break its dependency
59// on the proto package. It is still semantically correct for descriptor to
60// avoid using InternalMessageInfo, but it does incur some performance penalty.
61// This is acceptable for descriptor, which is a single proto file and is not
62// known to be in the hot path for any code.
63//
64// TODO: Remove this special-casing when the table-driven implementation has
65// been ported over to v2.
66func (f *fileInfo) protoPackage() protogen.GoImportPath {
67 if isDescriptor(f.File) {
68 return protoapiPackage
69 }
70 return protoPackage
71}
72
Damien Neil9c420a62018-09-27 15:26:33 -070073// GenerateFile generates the contents of a .pb.go file.
74func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070075 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070076 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070077 }
78
Joe Tsai9667c482018-12-05 15:42:52 -080079 // Collect all enums, messages, and extensions in a breadth-first order.
80 f.allEnums = append(f.allEnums, f.Enums...)
81 f.allMessages = append(f.allMessages, f.Messages...)
82 f.allExtensions = append(f.allExtensions, f.Extensions...)
83 walkMessages(f.Messages, func(m *protogen.Message) {
84 f.allEnums = append(f.allEnums, m.Enums...)
85 f.allMessages = append(f.allMessages, m.Messages...)
86 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070087 })
Damien Neilce36f8d2018-09-13 15:19:08 -070088
Joe Tsai9667c482018-12-05 15:42:52 -080089 // Derive a reverse mapping of enum and message pointers to their index
90 // in allEnums and allMessages.
91 if len(f.allEnums) > 0 {
92 f.allEnumsByPtr = make(map[*protogen.Enum]int)
93 for i, e := range f.allEnums {
94 f.allEnumsByPtr[e] = i
95 }
96 }
97 if len(f.allMessages) > 0 {
98 f.allMessagesByPtr = make(map[*protogen.Message]int)
99 for i, m := range f.allMessages {
100 f.allMessagesByPtr[m] = i
101 }
102 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800103
Damien Neil46abb572018-09-07 12:45:37 -0700104 // Determine the name of the var holding the file descriptor:
105 //
106 // fileDescriptor_<hash of filename>
107 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
108 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
109
Damien Neil220c2022018-08-15 11:24:18 -0700110 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700111 if f.Proto.GetOptions().GetDeprecated() {
112 g.P("// ", f.Desc.Path(), " is a deprecated file.")
113 } else {
114 g.P("// source: ", f.Desc.Path())
115 }
Damien Neil220c2022018-08-15 11:24:18 -0700116 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -0700117 const filePackageField = 2 // FileDescriptorProto.package
Damien Neilba1159f2018-10-17 12:53:18 -0700118 g.PrintLeadingComments(protogen.Location{
119 SourceFile: f.Proto.GetName(),
120 Path: []int32{filePackageField},
121 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700122 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700123 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700124 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700125
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800126 if !isDescriptor(file) {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800127 g.P("// This is a compile-time assertion to ensure that this generated file")
128 g.P("// is compatible with the proto package it is being compiled against.")
129 g.P("// A compilation error at this line likely means your copy of the")
130 g.P("// proto package needs to be updated.")
131 g.P("const _ = ", protoPackage.Ident(fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion)),
132 "// please upgrade the proto package")
133 g.P()
134 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700135
Damien Neil73ac8852018-09-17 15:11:24 -0700136 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
137 genImport(gen, g, f, imps.Get(i))
138 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700139 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700140 genEnum(gen, g, f, enum)
141 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700142 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700143 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700144 }
Joe Tsai9667c482018-12-05 15:42:52 -0800145 for _, extension := range f.allExtensions {
Damien Neil993c04d2018-09-14 15:41:11 -0700146 genExtension(gen, g, f, extension)
147 }
Damien Neil220c2022018-08-15 11:24:18 -0700148
Damien Neilce36f8d2018-09-13 15:19:08 -0700149 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700150 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800151 genReflectInitFunction(gen, g, f)
152 genReflectFileDescriptor(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700153}
154
Damien Neil73ac8852018-09-17 15:11:24 -0700155// walkMessages calls f on each message and all of its descendants.
156func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
157 for _, m := range messages {
158 f(m)
159 walkMessages(m.Messages, f)
160 }
161}
162
Damien Neild39efc82018-09-24 12:38:10 -0700163func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700164 impFile, ok := gen.FileByName(imp.Path())
165 if !ok {
166 return
167 }
168 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700169 // Don't generate imports or aliases for types in the same Go package.
170 return
171 }
Damien Neil40a08052018-10-29 09:07:41 -0700172 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700173 // referenced, because other code and tools depend on having the
174 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700175 if !imp.IsWeak {
176 g.Import(impFile.GoImportPath)
177 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700178 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700179 return
180 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700181 // TODO: An alternate approach to generating public imports might be
182 // to generate the imported file contents, parse it, and extract all
183 // exported identifiers from the AST to build a list of forwarding
184 // declarations.
185 //
186 // TODO: Consider whether this should generate recursive aliases. e.g.,
187 // if a.proto publicly imports b.proto publicly imports c.proto, should
188 // a.pb.go contain aliases for symbols defined in c.proto?
Damien Neil73ac8852018-09-17 15:11:24 -0700189 var enums []*protogen.Enum
190 enums = append(enums, impFile.Enums...)
191 walkMessages(impFile.Messages, func(message *protogen.Message) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700192 if message.Desc.IsMapEntry() {
193 return
194 }
Damien Neil73ac8852018-09-17 15:11:24 -0700195 enums = append(enums, message.Enums...)
Damien Neil2193e8d2018-10-09 12:49:13 -0700196 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800197 if !field.Desc.HasDefault() {
Damien Neil2193e8d2018-10-09 12:49:13 -0700198 continue
199 }
200 defVar := protogen.GoIdent{
201 GoImportPath: message.GoIdent.GoImportPath,
202 GoName: "Default_" + message.GoIdent.GoName + "_" + field.GoName,
203 }
204 decl := "const"
Damien Neil7e5c6472018-11-29 08:57:07 -0800205 switch field.Desc.Kind() {
206 case protoreflect.BytesKind:
Damien Neil2193e8d2018-10-09 12:49:13 -0700207 decl = "var"
Damien Neil7e5c6472018-11-29 08:57:07 -0800208 case protoreflect.FloatKind, protoreflect.DoubleKind:
209 f := field.Desc.Default().Float()
210 if math.IsInf(f, -1) || math.IsInf(f, 1) || math.IsNaN(f) {
211 decl = "var"
212 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700213 }
214 g.P(decl, " ", defVar.GoName, " = ", defVar)
215 }
Damien Neil73ac8852018-09-17 15:11:24 -0700216 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
217 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
218 for _, oneof := range message.Oneofs {
219 for _, field := range oneof.Fields {
220 typ := fieldOneofType(field)
221 g.P("type ", typ.GoName, " = ", typ)
222 }
223 }
224 g.P()
225 })
226 for _, enum := range enums {
227 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
228 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
229 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
230 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
231 g.P()
232 for _, value := range enum.Values {
233 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
234 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700235 }
Damien Neil6b541312018-10-29 09:14:14 -0700236 for _, ext := range impFile.Extensions {
237 ident := extensionVar(impFile, ext)
238 g.P("var ", ident.GoName, " = ", ident)
239 g.P()
240 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700241 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700242}
243
Damien Neild39efc82018-09-24 12:38:10 -0700244func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700245 // Trim the source_code_info from the descriptor.
246 // Marshal and gzip it.
Joe Tsaie1f8d502018-11-26 18:55:29 -0800247 descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto)
Damien Neil7779e052018-09-07 14:14:06 -0700248 descProto.SourceCodeInfo = nil
249 b, err := proto.Marshal(descProto)
250 if err != nil {
251 gen.Error(err)
252 return
253 }
254 var buf bytes.Buffer
255 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
256 w.Write(b)
257 w.Close()
258 b = buf.Bytes()
259
Damien Neil46abb572018-09-07 12:45:37 -0700260 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700261 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
262 for len(b) > 0 {
263 n := 16
264 if n > len(b) {
265 n = len(b)
266 }
267
268 s := ""
269 for _, c := range b[:n] {
270 s += fmt.Sprintf("0x%02x,", c)
271 }
272 g.P(s)
273
274 b = b[n:]
275 }
276 g.P("}")
277 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700278}
Damien Neilc7d07d92018-08-22 13:46:02 -0700279
Damien Neild39efc82018-09-24 12:38:10 -0700280func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700281 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700282 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700283 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800284 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700285 g.P("const (")
286 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700287 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700288 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700289 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800290 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700291 }
292 g.P(")")
293 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800294
295 // Generate support for protobuf reflection.
296 genReflectEnum(gen, g, f, enum)
297
Damien Neil46abb572018-09-07 12:45:37 -0700298 nameMap := enum.GoIdent.GoName + "_name"
299 g.P("var ", nameMap, " = map[int32]string{")
300 generated := make(map[protoreflect.EnumNumber]bool)
301 for _, value := range enum.Values {
302 duplicate := ""
303 if _, present := generated[value.Desc.Number()]; present {
304 duplicate = "// Duplicate value: "
305 }
306 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
307 generated[value.Desc.Number()] = true
308 }
309 g.P("}")
310 g.P()
311 valueMap := enum.GoIdent.GoName + "_value"
312 g.P("var ", valueMap, " = map[string]int32{")
313 for _, value := range enum.Values {
314 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
315 }
316 g.P("}")
317 g.P()
318 if enum.Desc.Syntax() != protoreflect.Proto3 {
319 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
320 g.P("p := new(", enum.GoIdent, ")")
321 g.P("*p = x")
322 g.P("return p")
323 g.P("}")
324 g.P()
325 }
326 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800327 g.P("return ", f.protoPackage().Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700328 g.P("}")
329 g.P()
330
Joe Tsai73903462018-12-14 12:22:41 -0800331 if enum.Desc.Syntax() == protoreflect.Proto2 {
Damien Neil46abb572018-09-07 12:45:37 -0700332 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800333 g.P("value, err := ", f.protoPackage().Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700334 g.P("if err != nil {")
335 g.P("return err")
336 g.P("}")
337 g.P("*x = ", enum.GoIdent, "(value)")
338 g.P("return nil")
339 g.P("}")
340 g.P()
341 }
342
343 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700344 for i := 1; i < len(enum.Location.Path); i += 2 {
345 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700346 }
347 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
348 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
349 g.P("}")
350 g.P()
351
Damien Neilea7baf42018-09-28 14:23:44 -0700352 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700353}
354
Damien Neil658051b2018-09-10 12:26:21 -0700355// enumRegistryName returns the name used to register an enum with the proto
356// package registry.
357//
358// Confusingly, this is <proto_package>.<go_ident>. This probably should have
359// been the full name of the proto enum type instead, but changing it at this
360// point would require thought.
361func enumRegistryName(enum *protogen.Enum) string {
362 // Find the FileDescriptor for this enum.
363 var desc protoreflect.Descriptor = enum.Desc
364 for {
365 p, ok := desc.Parent()
366 if !ok {
367 break
368 }
369 desc = p
370 }
371 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700372 if fdesc.Package() == "" {
373 return enum.GoIdent.GoName
374 }
Damien Neil658051b2018-09-10 12:26:21 -0700375 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
376}
377
Damien Neild39efc82018-09-24 12:38:10 -0700378func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700379 if message.Desc.IsMapEntry() {
380 return
381 }
382
Damien Neilba1159f2018-10-17 12:53:18 -0700383 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800384 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700385 if hasComment {
386 g.P("//")
387 }
388 g.P(deprecationComment(true))
389 }
Damien Neil162c1272018-10-04 12:42:37 -0700390 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700391 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700392 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700393 if field.OneofType != nil {
394 // It would be a bit simpler to iterate over the oneofs below,
395 // but generating the field here keeps the contents of the Go
396 // struct in the same order as the contents of the source
397 // .proto file.
398 if field == field.OneofType.Fields[0] {
399 genOneofField(gen, g, f, message, field.OneofType)
400 }
Damien Neil658051b2018-09-10 12:26:21 -0700401 continue
402 }
Damien Neilba1159f2018-10-17 12:53:18 -0700403 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700404 goType, pointer := fieldGoType(g, field)
405 if pointer {
406 goType = "*" + goType
407 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700408 tags := []string{
409 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
410 fmt.Sprintf("json:%q", fieldJSONTag(field)),
411 }
412 if field.Desc.IsMap() {
413 key := field.MessageType.Fields[0]
414 val := field.MessageType.Fields[1]
415 tags = append(tags,
416 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
417 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
418 )
419 }
Damien Neil162c1272018-10-04 12:42:37 -0700420 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700421 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800422 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700423 }
424 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700425
426 if message.Desc.ExtensionRanges().Len() > 0 {
427 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800428 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700429 tags = append(tags, `protobuf_messageset:"1"`)
430 }
431 tags = append(tags, `json:"-"`)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800432 g.P(f.protoPackage().Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700433 }
Damien Neil658051b2018-09-10 12:26:21 -0700434 g.P("XXX_unrecognized []byte `json:\"-\"`")
435 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700436 g.P("}")
437 g.P()
438
Joe Tsaib6405bd2018-11-15 14:44:37 -0800439 // Generate support for protobuf reflection.
440 genReflectMessage(gen, g, f, message)
441
Damien Neila1c6abc2018-09-12 13:36:34 -0700442 // Reset
443 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
444 // String
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800445 g.P("func (m *", message.GoIdent, ") String() string { return ", f.protoPackage().Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700446 // ProtoMessage
447 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
448 // Descriptor
449 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700450 for i := 1; i < len(message.Location.Path); i += 2 {
451 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700452 }
453 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
454 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
455 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700456 g.P()
457
458 // ExtensionRangeArray
459 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800460 protoExtRange := f.protoPackage().Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700461 extRangeVar := "extRange_" + message.GoIdent.GoName
462 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
463 for i := 0; i < extranges.Len(); i++ {
464 r := extranges.Get(i)
465 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
466 }
467 g.P("}")
468 g.P()
469 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
470 g.P("return ", extRangeVar)
471 g.P("}")
472 g.P()
473 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700474
Damien Neilea7baf42018-09-28 14:23:44 -0700475 genWellKnownType(g, "*", message.GoIdent, message.Desc)
476
Damien Neila1c6abc2018-09-12 13:36:34 -0700477 // Table-driven proto support.
478 //
479 // TODO: It does not scale to keep adding another method for every
480 // operation on protos that we want to switch over to using the
481 // table-driven approach. Instead, we should only add a single method
482 // that allows getting access to the *InternalMessageInfo struct and then
483 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800484 if !isDescriptor(f.File) {
485 // NOTE: We avoid adding table-driven support for descriptor proto
486 // since this depends on the v1 proto package, which would eventually
487 // need to depend on the descriptor itself.
488 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
489 // XXX_Unmarshal
490 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
491 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
492 g.P("}")
493 // XXX_Marshal
494 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
495 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
496 g.P("}")
497 // XXX_Merge
498 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
499 g.P(messageInfoVar, ".Merge(m, src)")
500 g.P("}")
501 // XXX_Size
502 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
503 g.P("return ", messageInfoVar, ".Size(m)")
504 g.P("}")
505 // XXX_DiscardUnknown
506 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
507 g.P(messageInfoVar, ".DiscardUnknown(m)")
508 g.P("}")
509 g.P()
510 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
511 g.P()
512 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700513
Damien Neilebc699d2018-09-13 08:50:13 -0700514 // Constants and vars holding the default values of fields.
515 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800516 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700517 continue
518 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700519 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700520 def := field.Desc.Default()
521 switch field.Desc.Kind() {
522 case protoreflect.StringKind:
523 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
524 case protoreflect.BytesKind:
525 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
526 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700527 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700528 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700529 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700530 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
531 case protoreflect.FloatKind, protoreflect.DoubleKind:
532 // Floating point numbers need extra handling for -Inf/Inf/NaN.
533 f := field.Desc.Default().Float()
534 goType := "float64"
535 if field.Desc.Kind() == protoreflect.FloatKind {
536 goType = "float32"
537 }
538 // funcCall returns a call to a function in the math package,
539 // possibly converting the result to float32.
540 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800541 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700542 if goType != "float64" {
543 s = goType + "(" + s + ")"
544 }
545 return s
546 }
547 switch {
548 case math.IsInf(f, -1):
549 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
550 case math.IsInf(f, 1):
551 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
552 case math.IsNaN(f):
553 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
554 default:
Damien Neil982684b2018-09-28 14:12:41 -0700555 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700556 }
557 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700558 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700559 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
560 }
561 }
562 g.P()
563
Damien Neil77f82fe2018-09-13 10:59:17 -0700564 // Getters.
565 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700566 if field.OneofType != nil {
567 if field == field.OneofType.Fields[0] {
568 genOneofTypes(gen, g, f, message, field.OneofType)
569 }
570 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700571 goType, pointer := fieldGoType(g, field)
572 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800573 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700574 g.P(deprecationComment(true))
575 }
Damien Neil162c1272018-10-04 12:42:37 -0700576 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700577 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
578 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700579 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700580 g.P("return x.", field.GoName)
581 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700582 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700583 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
584 g.P("if m != nil {")
585 } else {
586 g.P("if m != nil && m.", field.GoName, " != nil {")
587 }
588 star := ""
589 if pointer {
590 star = "*"
591 }
592 g.P("return ", star, " m.", field.GoName)
593 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700594 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700595 g.P("return ", defaultValue)
596 g.P("}")
597 g.P()
598 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700599
Damien Neil1fa78d82018-09-13 13:12:36 -0700600 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800601 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700602 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700603}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700604
Damien Neil77f82fe2018-09-13 10:59:17 -0700605// fieldGoType returns the Go type used for a field.
606//
607// If it returns pointer=true, the struct field is a pointer to the type.
608func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700609 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700610 switch field.Desc.Kind() {
611 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700612 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700613 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700615 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700617 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700619 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700620 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700621 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700623 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700625 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700626 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700627 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700629 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = "[]byte"
631 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700632 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700633 if field.Desc.IsMap() {
634 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
635 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
636 return fmt.Sprintf("map[%v]%v", keyType, valType), false
637 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700638 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
639 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700640 }
641 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700642 goType = "[]" + goType
643 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700644 }
Damien Neil44000a12018-10-24 12:31:16 -0700645 // Extension fields always have pointer type, even when defined in a proto3 file.
646 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700647 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700648 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700649 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700650}
651
652func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700653 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700654 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700655 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700656 }
Joe Tsai05828db2018-11-01 13:52:16 -0700657 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700658}
659
Damien Neil77f82fe2018-09-13 10:59:17 -0700660func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
661 if field.Desc.Cardinality() == protoreflect.Repeated {
662 return "nil"
663 }
Joe Tsai9667c482018-12-05 15:42:52 -0800664 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700665 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700666 if field.Desc.Kind() == protoreflect.BytesKind {
667 return "append([]byte(nil), " + defVarName + "...)"
668 }
669 return defVarName
670 }
671 switch field.Desc.Kind() {
672 case protoreflect.BoolKind:
673 return "false"
674 case protoreflect.StringKind:
675 return `""`
676 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
677 return "nil"
678 case protoreflect.EnumKind:
679 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
680 default:
681 return "0"
682 }
683}
684
Damien Neil658051b2018-09-10 12:26:21 -0700685func fieldJSONTag(field *protogen.Field) string {
686 return string(field.Desc.Name()) + ",omitempty"
687}
688
Damien Neild39efc82018-09-24 12:38:10 -0700689func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700690 // Special case for proto2 message sets: If this extension is extending
691 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
692 // then drop that last component.
693 //
694 // TODO: This should be implemented in the text formatter rather than the generator.
695 // In addition, the situation for when to apply this special case is implemented
696 // differently in other languages:
697 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
698 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700699 if n, ok := isExtensionMessageSetElement(extension); ok {
700 name = n
Damien Neil154da982018-09-19 13:21:58 -0700701 }
702
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800703 g.P("var ", extensionVar(f.File, extension), " = &", f.protoPackage().Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700704 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
705 goType, pointer := fieldGoType(g, extension)
706 if pointer {
707 goType = "*" + goType
708 }
709 g.P("ExtensionType: (", goType, ")(nil),")
710 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700711 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700712 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
713 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
714 g.P("}")
715 g.P()
716}
717
Damien Neil62386962018-10-30 10:35:48 -0700718// isExtensionMessageSetELement returns the adjusted name of an extension
719// which extends proto2.bridge.MessageSet.
720func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800721 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700722 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
723 return "", false
724 }
725 if extension.ParentMessage == nil {
726 // This case shouldn't be given special handling at all--we're
727 // only supposed to drop the ".message_set_extension" for
728 // extensions defined within a message (i.e., the extension
729 // takes the message's name).
730 //
731 // This matches the behavior of the v1 generator, however.
732 //
733 // TODO: See if we can drop this case.
734 name = extension.Desc.FullName()
735 name = name[:len(name)-len("message_set_extension")]
736 return name, true
737 }
738 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700739}
740
Damien Neil993c04d2018-09-14 15:41:11 -0700741// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700742func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700743 name := "E_"
744 if extension.ParentMessage != nil {
745 name += extension.ParentMessage.GoIdent.GoName + "_"
746 }
747 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800748 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700749}
750
Damien Neilce36f8d2018-09-13 15:19:08 -0700751// genInitFunction generates an init function that registers the types in the
752// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700753func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neilce36f8d2018-09-13 15:19:08 -0700754 g.P("func init() {")
Joe Tsai9667c482018-12-05 15:42:52 -0800755 g.P(f.protoPackage().Ident("RegisterFile"), "(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ")")
Damien Neil154da982018-09-19 13:21:58 -0700756 for _, enum := range f.allEnums {
757 name := enum.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800758 g.P(f.protoPackage().Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700759 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700760 for _, message := range f.allMessages {
761 if message.Desc.IsMapEntry() {
762 continue
763 }
764
765 name := message.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800766 g.P(f.protoPackage().Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700767
768 // Types of map fields, sorted by the name of the field message type.
769 var mapFields []*protogen.Field
770 for _, field := range message.Fields {
771 if field.Desc.IsMap() {
772 mapFields = append(mapFields, field)
773 }
774 }
775 sort.Slice(mapFields, func(i, j int) bool {
776 ni := mapFields[i].MessageType.Desc.FullName()
777 nj := mapFields[j].MessageType.Desc.FullName()
778 return ni < nj
779 })
780 for _, field := range mapFields {
781 typeName := string(field.MessageType.Desc.FullName())
782 goType, _ := fieldGoType(g, field)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800783 g.P(f.protoPackage().Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700784 }
785 }
Joe Tsai9667c482018-12-05 15:42:52 -0800786 for _, extension := range f.allExtensions {
787 g.P(f.protoPackage().Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil993c04d2018-09-14 15:41:11 -0700788 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700789 g.P("}")
790 g.P()
791}
792
Damien Neil55fe1c02018-09-17 15:11:24 -0700793// deprecationComment returns a standard deprecation comment if deprecated is true.
794func deprecationComment(deprecated bool) string {
795 if !deprecated {
796 return ""
797 }
798 return "// Deprecated: Do not use."
799}
800
Damien Neilea7baf42018-09-28 14:23:44 -0700801func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700802 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700803 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700804 g.P()
805 }
806}
807
808// Names of messages and enums for which we will generate XXX_WellKnownType methods.
809var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700810 "google.protobuf.Any": true,
811 "google.protobuf.Duration": true,
812 "google.protobuf.Empty": true,
813 "google.protobuf.Struct": true,
814 "google.protobuf.Timestamp": true,
815
816 "google.protobuf.BoolValue": true,
817 "google.protobuf.BytesValue": true,
818 "google.protobuf.DoubleValue": true,
819 "google.protobuf.FloatValue": true,
820 "google.protobuf.Int32Value": true,
821 "google.protobuf.Int64Value": true,
822 "google.protobuf.ListValue": true,
823 "google.protobuf.NullValue": true,
824 "google.protobuf.StringValue": true,
825 "google.protobuf.UInt32Value": true,
826 "google.protobuf.UInt64Value": true,
827 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700828}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800829
830// genOneofField generates the struct field for a oneof.
831func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
832 if g.PrintLeadingComments(oneof.Location) {
833 g.P("//")
834 }
835 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
836 for _, field := range oneof.Fields {
837 g.PrintLeadingComments(field.Location)
838 g.P("//\t*", fieldOneofType(field))
839 }
840 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
841 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
842}
843
844// genOneofTypes generates the interface type used for a oneof field,
845// and the wrapper types that satisfy that interface.
846//
847// It also generates the getter method for the parent oneof field
848// (but not the member fields).
849func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
850 ifName := oneofInterfaceName(oneof)
851 g.P("type ", ifName, " interface {")
852 g.P(ifName, "()")
853 g.P("}")
854 g.P()
855 for _, field := range oneof.Fields {
856 name := fieldOneofType(field)
857 g.Annotate(name.GoName, field.Location)
858 g.Annotate(name.GoName+"."+field.GoName, field.Location)
859 g.P("type ", name, " struct {")
860 goType, _ := fieldGoType(g, field)
861 tags := []string{
862 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
863 }
864 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
865 g.P("}")
866 g.P()
867 }
868 for _, field := range oneof.Fields {
869 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
870 g.P()
871 }
872 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
873 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
874 g.P("if m != nil {")
875 g.P("return m.", oneofFieldName(oneof))
876 g.P("}")
877 g.P("return nil")
878 g.P("}")
879 g.P()
880}
881
882// oneofFieldName returns the name of the struct field holding the oneof value.
883//
884// This function is trivial, but pulling out the name like this makes it easier
885// to experiment with alternative oneof implementations.
886func oneofFieldName(oneof *protogen.Oneof) string {
887 return oneof.GoName
888}
889
890// oneofInterfaceName returns the name of the interface type implemented by
891// the oneof field value types.
892func oneofInterfaceName(oneof *protogen.Oneof) string {
893 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
894}
895
896// genOneofWrappers generates the XXX_OneofWrappers method for a message.
897func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
898 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
899 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
900 g.P("return []interface{}{")
901 for _, oneof := range message.Oneofs {
902 for _, field := range oneof.Fields {
903 g.P("(*", fieldOneofType(field), ")(nil),")
904 }
905 }
906 g.P("}")
907 g.P("}")
908 g.P()
909}
910
911// fieldOneofType returns the wrapper type used to represent a field in a oneof.
912func fieldOneofType(field *protogen.Field) protogen.GoIdent {
913 ident := protogen.GoIdent{
914 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
915 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
916 }
917 // Check for collisions with nested messages or enums.
918 //
919 // This conflict resolution is incomplete: Among other things, it
920 // does not consider collisions with other oneof field types.
921 //
922 // TODO: Consider dropping this entirely. Detecting conflicts and
923 // producing an error is almost certainly better than permuting
924 // field and type names in mostly unpredictable ways.
925Loop:
926 for {
927 for _, message := range field.ParentMessage.Messages {
928 if message.GoIdent == ident {
929 ident.GoName += "_"
930 continue Loop
931 }
932 }
933 for _, enum := range field.ParentMessage.Enums {
934 if enum.GoIdent == ident {
935 ident.GoName += "_"
936 continue Loop
937 }
938 }
939 return ident
940 }
941}