blob: 5e6b7b769849977b2662578a86d53bdf6677b2b4 [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 Neil7bf3ce22018-12-21 15:54:06 -080014 "go/ast"
15 "go/parser"
16 "go/token"
Damien Neilebc699d2018-09-13 08:50:13 -070017 "math"
Damien Neilce36f8d2018-09-13 15:19:08 -070018 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070019 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070020 "strings"
Damien Neil7bf3ce22018-12-21 15:54:06 -080021 "unicode"
22 "unicode/utf8"
Damien Neil7779e052018-09-07 14:14:06 -070023
24 "github.com/golang/protobuf/proto"
Joe Tsai05828db2018-11-01 13:52:16 -070025 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai01ab2962018-09-21 17:44:00 -070026 "github.com/golang/protobuf/v2/protogen"
27 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080028
29 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070030)
31
Damien Neild4127922018-09-12 11:13:49 -070032// generatedCodeVersion indicates a version of the generated code.
33// It is incremented whenever an incompatibility between the generated code and
34// proto package is introduced; the generated code references
35// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
Joe Tsaid7e97bc2018-11-26 12:57:27 -080036const generatedCodeVersion = 3
Damien Neild4127922018-09-12 11:13:49 -070037
Joe Tsaic1c17aa2018-11-16 11:14:14 -080038const (
Joe Tsai24ceb2b2018-12-04 22:53:56 -080039 fmtPackage = protogen.GoImportPath("fmt")
40 mathPackage = protogen.GoImportPath("math")
41 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
42 protoapiPackage = protogen.GoImportPath("github.com/golang/protobuf/protoapi")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080043)
Damien Neil46abb572018-09-07 12:45:37 -070044
Damien Neild39efc82018-09-24 12:38:10 -070045type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070046 *protogen.File
Damien Neil46abb572018-09-07 12:45:37 -070047 descriptorVar string // var containing the gzipped FileDescriptorProto
Joe Tsaib6405bd2018-11-15 14:44:37 -080048
Joe Tsai9667c482018-12-05 15:42:52 -080049 allEnums []*protogen.Enum
50 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
51 allMessages []*protogen.Message
52 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
53 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070054}
55
Joe Tsai24ceb2b2018-12-04 22:53:56 -080056// protoPackage returns the package to import, which is either the protoPackage
57// or the protoapiPackage constant.
58//
59// This special casing exists because we are unable to move InternalMessageInfo
60// to protoapi since the implementation behind that logic is heavy and
61// too intricately connected to other parts of the proto package.
62// The descriptor proto is special in that it avoids using InternalMessageInfo
63// so that it is able to depend solely on protoapi and break its dependency
64// on the proto package. It is still semantically correct for descriptor to
65// avoid using InternalMessageInfo, but it does incur some performance penalty.
66// This is acceptable for descriptor, which is a single proto file and is not
67// known to be in the hot path for any code.
68//
69// TODO: Remove this special-casing when the table-driven implementation has
70// been ported over to v2.
71func (f *fileInfo) protoPackage() protogen.GoImportPath {
72 if isDescriptor(f.File) {
73 return protoapiPackage
74 }
75 return protoPackage
76}
77
Damien Neil9c420a62018-09-27 15:26:33 -070078// GenerateFile generates the contents of a .pb.go file.
79func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070080 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070081 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070082 }
83
Joe Tsai9667c482018-12-05 15:42:52 -080084 // Collect all enums, messages, and extensions in a breadth-first order.
85 f.allEnums = append(f.allEnums, f.Enums...)
86 f.allMessages = append(f.allMessages, f.Messages...)
87 f.allExtensions = append(f.allExtensions, f.Extensions...)
88 walkMessages(f.Messages, func(m *protogen.Message) {
89 f.allEnums = append(f.allEnums, m.Enums...)
90 f.allMessages = append(f.allMessages, m.Messages...)
91 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070092 })
Damien Neilce36f8d2018-09-13 15:19:08 -070093
Joe Tsai9667c482018-12-05 15:42:52 -080094 // Derive a reverse mapping of enum and message pointers to their index
95 // in allEnums and allMessages.
96 if len(f.allEnums) > 0 {
97 f.allEnumsByPtr = make(map[*protogen.Enum]int)
98 for i, e := range f.allEnums {
99 f.allEnumsByPtr[e] = i
100 }
101 }
102 if len(f.allMessages) > 0 {
103 f.allMessagesByPtr = make(map[*protogen.Message]int)
104 for i, m := range f.allMessages {
105 f.allMessagesByPtr[m] = i
106 }
107 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800108
Damien Neil46abb572018-09-07 12:45:37 -0700109 // Determine the name of the var holding the file descriptor:
110 //
111 // fileDescriptor_<hash of filename>
112 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
113 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
114
Damien Neil220c2022018-08-15 11:24:18 -0700115 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700116 if f.Proto.GetOptions().GetDeprecated() {
117 g.P("// ", f.Desc.Path(), " is a deprecated file.")
118 } else {
119 g.P("// source: ", f.Desc.Path())
120 }
Damien Neil220c2022018-08-15 11:24:18 -0700121 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -0700122 const filePackageField = 2 // FileDescriptorProto.package
Damien Neilba1159f2018-10-17 12:53:18 -0700123 g.PrintLeadingComments(protogen.Location{
124 SourceFile: f.Proto.GetName(),
125 Path: []int32{filePackageField},
126 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700127 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700128 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700129 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700130
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800131 if !isDescriptor(file) {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800132 g.P("// This is a compile-time assertion to ensure that this generated file")
133 g.P("// is compatible with the proto package it is being compiled against.")
134 g.P("// A compilation error at this line likely means your copy of the")
135 g.P("// proto package needs to be updated.")
136 g.P("const _ = ", protoPackage.Ident(fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion)),
137 "// please upgrade the proto package")
138 g.P()
139 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700140
Damien Neil73ac8852018-09-17 15:11:24 -0700141 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
142 genImport(gen, g, f, imps.Get(i))
143 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700144 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700145 genEnum(gen, g, f, enum)
146 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700147 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700148 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700149 }
Joe Tsai9667c482018-12-05 15:42:52 -0800150 for _, extension := range f.allExtensions {
Damien Neil993c04d2018-09-14 15:41:11 -0700151 genExtension(gen, g, f, extension)
152 }
Damien Neil220c2022018-08-15 11:24:18 -0700153
Damien Neilce36f8d2018-09-13 15:19:08 -0700154 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700155 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800156 genReflectInitFunction(gen, g, f)
157 genReflectFileDescriptor(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700158}
159
Damien Neil73ac8852018-09-17 15:11:24 -0700160// walkMessages calls f on each message and all of its descendants.
161func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
162 for _, m := range messages {
163 f(m)
164 walkMessages(m.Messages, f)
165 }
166}
167
Damien Neild39efc82018-09-24 12:38:10 -0700168func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700169 impFile, ok := gen.FileByName(imp.Path())
170 if !ok {
171 return
172 }
173 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700174 // Don't generate imports or aliases for types in the same Go package.
175 return
176 }
Damien Neil40a08052018-10-29 09:07:41 -0700177 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700178 // referenced, because other code and tools depend on having the
179 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700180 if !imp.IsWeak {
181 g.Import(impFile.GoImportPath)
182 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700183 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700184 return
185 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800186
187 // Generate public imports by generating the imported file, parsing it,
188 // and extracting every symbol that should receive a forwarding declaration.
189 impGen := gen.NewGeneratedFile("temp.go", impFile.GoImportPath)
190 impGen.Skip()
191 GenerateFile(gen, impFile, impGen)
192 b, err := impGen.Content()
193 if err != nil {
194 gen.Error(err)
195 return
196 }
197 fset := token.NewFileSet()
198 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
199 if err != nil {
200 gen.Error(err)
201 return
202 }
203 genForward := func(tok token.Token, name string) {
204 // Don't import unexported symbols.
205 r, _ := utf8.DecodeRuneInString(name)
206 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700207 return
208 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800209 // Don't import the FileDescriptor.
210 if name == impFile.GoDescriptorIdent.GoName {
211 return
212 }
213 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
214 }
215 g.P("// Symbols defined in public import of ", imp.Path())
216 g.P()
217 for _, decl := range astFile.Decls {
218 switch decl := decl.(type) {
219 case *ast.GenDecl:
220 for _, spec := range decl.Specs {
221 switch spec := spec.(type) {
222 case *ast.TypeSpec:
223 genForward(decl.Tok, spec.Name.Name)
224 case *ast.ValueSpec:
225 for _, name := range spec.Names {
226 genForward(decl.Tok, name.Name)
227 }
228 case *ast.ImportSpec:
229 default:
230 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800231 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700232 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700233 }
Damien Neil6b541312018-10-29 09:14:14 -0700234 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700235 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700236}
237
Damien Neild39efc82018-09-24 12:38:10 -0700238func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700239 // Trim the source_code_info from the descriptor.
240 // Marshal and gzip it.
Joe Tsaie1f8d502018-11-26 18:55:29 -0800241 descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto)
Damien Neil7779e052018-09-07 14:14:06 -0700242 descProto.SourceCodeInfo = nil
243 b, err := proto.Marshal(descProto)
244 if err != nil {
245 gen.Error(err)
246 return
247 }
248 var buf bytes.Buffer
249 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
250 w.Write(b)
251 w.Close()
252 b = buf.Bytes()
253
Damien Neil46abb572018-09-07 12:45:37 -0700254 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700255 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
256 for len(b) > 0 {
257 n := 16
258 if n > len(b) {
259 n = len(b)
260 }
261
262 s := ""
263 for _, c := range b[:n] {
264 s += fmt.Sprintf("0x%02x,", c)
265 }
266 g.P(s)
267
268 b = b[n:]
269 }
270 g.P("}")
271 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700272}
Damien Neilc7d07d92018-08-22 13:46:02 -0700273
Damien Neild39efc82018-09-24 12:38:10 -0700274func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700275 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700276 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700277 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800278 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700279 g.P("const (")
280 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700281 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700282 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700283 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800284 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700285 }
286 g.P(")")
287 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800288
289 // Generate support for protobuf reflection.
290 genReflectEnum(gen, g, f, enum)
291
Damien Neil46abb572018-09-07 12:45:37 -0700292 nameMap := enum.GoIdent.GoName + "_name"
293 g.P("var ", nameMap, " = map[int32]string{")
294 generated := make(map[protoreflect.EnumNumber]bool)
295 for _, value := range enum.Values {
296 duplicate := ""
297 if _, present := generated[value.Desc.Number()]; present {
298 duplicate = "// Duplicate value: "
299 }
300 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
301 generated[value.Desc.Number()] = true
302 }
303 g.P("}")
304 g.P()
305 valueMap := enum.GoIdent.GoName + "_value"
306 g.P("var ", valueMap, " = map[string]int32{")
307 for _, value := range enum.Values {
308 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
309 }
310 g.P("}")
311 g.P()
312 if enum.Desc.Syntax() != protoreflect.Proto3 {
313 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
314 g.P("p := new(", enum.GoIdent, ")")
315 g.P("*p = x")
316 g.P("return p")
317 g.P("}")
318 g.P()
319 }
320 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800321 g.P("return ", f.protoPackage().Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700322 g.P("}")
323 g.P()
324
Joe Tsai73903462018-12-14 12:22:41 -0800325 if enum.Desc.Syntax() == protoreflect.Proto2 {
Damien Neil46abb572018-09-07 12:45:37 -0700326 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800327 g.P("value, err := ", f.protoPackage().Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700328 g.P("if err != nil {")
329 g.P("return err")
330 g.P("}")
331 g.P("*x = ", enum.GoIdent, "(value)")
332 g.P("return nil")
333 g.P("}")
334 g.P()
335 }
336
337 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700338 for i := 1; i < len(enum.Location.Path); i += 2 {
339 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700340 }
341 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
342 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
343 g.P("}")
344 g.P()
345
Damien Neilea7baf42018-09-28 14:23:44 -0700346 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700347}
348
Damien Neil658051b2018-09-10 12:26:21 -0700349// enumRegistryName returns the name used to register an enum with the proto
350// package registry.
351//
352// Confusingly, this is <proto_package>.<go_ident>. This probably should have
353// been the full name of the proto enum type instead, but changing it at this
354// point would require thought.
355func enumRegistryName(enum *protogen.Enum) string {
356 // Find the FileDescriptor for this enum.
357 var desc protoreflect.Descriptor = enum.Desc
358 for {
359 p, ok := desc.Parent()
360 if !ok {
361 break
362 }
363 desc = p
364 }
365 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700366 if fdesc.Package() == "" {
367 return enum.GoIdent.GoName
368 }
Damien Neil658051b2018-09-10 12:26:21 -0700369 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
370}
371
Damien Neild39efc82018-09-24 12:38:10 -0700372func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700373 if message.Desc.IsMapEntry() {
374 return
375 }
376
Damien Neilba1159f2018-10-17 12:53:18 -0700377 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800378 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700379 if hasComment {
380 g.P("//")
381 }
382 g.P(deprecationComment(true))
383 }
Damien Neil162c1272018-10-04 12:42:37 -0700384 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700385 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700386 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700387 if field.OneofType != nil {
388 // It would be a bit simpler to iterate over the oneofs below,
389 // but generating the field here keeps the contents of the Go
390 // struct in the same order as the contents of the source
391 // .proto file.
392 if field == field.OneofType.Fields[0] {
393 genOneofField(gen, g, f, message, field.OneofType)
394 }
Damien Neil658051b2018-09-10 12:26:21 -0700395 continue
396 }
Damien Neilba1159f2018-10-17 12:53:18 -0700397 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700398 goType, pointer := fieldGoType(g, field)
399 if pointer {
400 goType = "*" + goType
401 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700402 tags := []string{
403 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
404 fmt.Sprintf("json:%q", fieldJSONTag(field)),
405 }
406 if field.Desc.IsMap() {
407 key := field.MessageType.Fields[0]
408 val := field.MessageType.Fields[1]
409 tags = append(tags,
410 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
411 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
412 )
413 }
Damien Neil162c1272018-10-04 12:42:37 -0700414 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700415 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800416 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700417 }
418 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700419
420 if message.Desc.ExtensionRanges().Len() > 0 {
421 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800422 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700423 tags = append(tags, `protobuf_messageset:"1"`)
424 }
425 tags = append(tags, `json:"-"`)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800426 g.P(f.protoPackage().Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700427 }
Damien Neil658051b2018-09-10 12:26:21 -0700428 g.P("XXX_unrecognized []byte `json:\"-\"`")
429 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700430 g.P("}")
431 g.P()
432
Joe Tsaib6405bd2018-11-15 14:44:37 -0800433 // Generate support for protobuf reflection.
434 genReflectMessage(gen, g, f, message)
435
Damien Neila1c6abc2018-09-12 13:36:34 -0700436 // Reset
437 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
438 // String
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800439 g.P("func (m *", message.GoIdent, ") String() string { return ", f.protoPackage().Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700440 // ProtoMessage
441 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
442 // Descriptor
443 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700444 for i := 1; i < len(message.Location.Path); i += 2 {
445 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700446 }
447 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
448 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
449 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700450 g.P()
451
452 // ExtensionRangeArray
453 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800454 protoExtRange := f.protoPackage().Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700455 extRangeVar := "extRange_" + message.GoIdent.GoName
456 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
457 for i := 0; i < extranges.Len(); i++ {
458 r := extranges.Get(i)
459 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
460 }
461 g.P("}")
462 g.P()
463 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
464 g.P("return ", extRangeVar)
465 g.P("}")
466 g.P()
467 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700468
Damien Neilea7baf42018-09-28 14:23:44 -0700469 genWellKnownType(g, "*", message.GoIdent, message.Desc)
470
Damien Neila1c6abc2018-09-12 13:36:34 -0700471 // Table-driven proto support.
472 //
473 // TODO: It does not scale to keep adding another method for every
474 // operation on protos that we want to switch over to using the
475 // table-driven approach. Instead, we should only add a single method
476 // that allows getting access to the *InternalMessageInfo struct and then
477 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800478 if !isDescriptor(f.File) {
479 // NOTE: We avoid adding table-driven support for descriptor proto
480 // since this depends on the v1 proto package, which would eventually
481 // need to depend on the descriptor itself.
482 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
483 // XXX_Unmarshal
484 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
485 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
486 g.P("}")
487 // XXX_Marshal
488 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
489 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
490 g.P("}")
491 // XXX_Merge
492 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
493 g.P(messageInfoVar, ".Merge(m, src)")
494 g.P("}")
495 // XXX_Size
496 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
497 g.P("return ", messageInfoVar, ".Size(m)")
498 g.P("}")
499 // XXX_DiscardUnknown
500 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
501 g.P(messageInfoVar, ".DiscardUnknown(m)")
502 g.P("}")
503 g.P()
504 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
505 g.P()
506 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700507
Damien Neilebc699d2018-09-13 08:50:13 -0700508 // Constants and vars holding the default values of fields.
509 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800510 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700511 continue
512 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700513 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700514 def := field.Desc.Default()
515 switch field.Desc.Kind() {
516 case protoreflect.StringKind:
517 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
518 case protoreflect.BytesKind:
519 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
520 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700521 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700522 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700523 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700524 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
525 case protoreflect.FloatKind, protoreflect.DoubleKind:
526 // Floating point numbers need extra handling for -Inf/Inf/NaN.
527 f := field.Desc.Default().Float()
528 goType := "float64"
529 if field.Desc.Kind() == protoreflect.FloatKind {
530 goType = "float32"
531 }
532 // funcCall returns a call to a function in the math package,
533 // possibly converting the result to float32.
534 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800535 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700536 if goType != "float64" {
537 s = goType + "(" + s + ")"
538 }
539 return s
540 }
541 switch {
542 case math.IsInf(f, -1):
543 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
544 case math.IsInf(f, 1):
545 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
546 case math.IsNaN(f):
547 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
548 default:
Damien Neil982684b2018-09-28 14:12:41 -0700549 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700550 }
551 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700552 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700553 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
554 }
555 }
556 g.P()
557
Damien Neil77f82fe2018-09-13 10:59:17 -0700558 // Getters.
559 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700560 if field.OneofType != nil {
561 if field == field.OneofType.Fields[0] {
562 genOneofTypes(gen, g, f, message, field.OneofType)
563 }
564 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700565 goType, pointer := fieldGoType(g, field)
566 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800567 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700568 g.P(deprecationComment(true))
569 }
Damien Neil162c1272018-10-04 12:42:37 -0700570 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700571 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
572 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700573 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700574 g.P("return x.", field.GoName)
575 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700576 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700577 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
578 g.P("if m != nil {")
579 } else {
580 g.P("if m != nil && m.", field.GoName, " != nil {")
581 }
582 star := ""
583 if pointer {
584 star = "*"
585 }
586 g.P("return ", star, " m.", field.GoName)
587 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700588 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700589 g.P("return ", defaultValue)
590 g.P("}")
591 g.P()
592 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700593
Damien Neil1fa78d82018-09-13 13:12:36 -0700594 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800595 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700596 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700597}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700598
Damien Neil77f82fe2018-09-13 10:59:17 -0700599// fieldGoType returns the Go type used for a field.
600//
601// If it returns pointer=true, the struct field is a pointer to the type.
602func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700603 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700604 switch field.Desc.Kind() {
605 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700606 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700607 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700608 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700609 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700610 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700611 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700612 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700613 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700615 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700617 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700619 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700620 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700621 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700623 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 goType = "[]byte"
625 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700626 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700627 if field.Desc.IsMap() {
628 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
629 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
630 return fmt.Sprintf("map[%v]%v", keyType, valType), false
631 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700632 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
633 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700634 }
635 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700636 goType = "[]" + goType
637 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700638 }
Damien Neil44000a12018-10-24 12:31:16 -0700639 // Extension fields always have pointer type, even when defined in a proto3 file.
640 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700641 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700642 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700643 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700644}
645
646func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700647 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700648 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700649 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700650 }
Joe Tsai05828db2018-11-01 13:52:16 -0700651 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700652}
653
Damien Neil77f82fe2018-09-13 10:59:17 -0700654func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
655 if field.Desc.Cardinality() == protoreflect.Repeated {
656 return "nil"
657 }
Joe Tsai9667c482018-12-05 15:42:52 -0800658 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700659 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700660 if field.Desc.Kind() == protoreflect.BytesKind {
661 return "append([]byte(nil), " + defVarName + "...)"
662 }
663 return defVarName
664 }
665 switch field.Desc.Kind() {
666 case protoreflect.BoolKind:
667 return "false"
668 case protoreflect.StringKind:
669 return `""`
670 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
671 return "nil"
672 case protoreflect.EnumKind:
673 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
674 default:
675 return "0"
676 }
677}
678
Damien Neil658051b2018-09-10 12:26:21 -0700679func fieldJSONTag(field *protogen.Field) string {
680 return string(field.Desc.Name()) + ",omitempty"
681}
682
Damien Neild39efc82018-09-24 12:38:10 -0700683func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700684 // Special case for proto2 message sets: If this extension is extending
685 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
686 // then drop that last component.
687 //
688 // TODO: This should be implemented in the text formatter rather than the generator.
689 // In addition, the situation for when to apply this special case is implemented
690 // differently in other languages:
691 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
692 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700693 if n, ok := isExtensionMessageSetElement(extension); ok {
694 name = n
Damien Neil154da982018-09-19 13:21:58 -0700695 }
696
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800697 g.P("var ", extensionVar(f.File, extension), " = &", f.protoPackage().Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700698 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
699 goType, pointer := fieldGoType(g, extension)
700 if pointer {
701 goType = "*" + goType
702 }
703 g.P("ExtensionType: (", goType, ")(nil),")
704 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700705 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700706 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
707 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
708 g.P("}")
709 g.P()
710}
711
Damien Neil62386962018-10-30 10:35:48 -0700712// isExtensionMessageSetELement returns the adjusted name of an extension
713// which extends proto2.bridge.MessageSet.
714func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800715 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700716 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
717 return "", false
718 }
719 if extension.ParentMessage == nil {
720 // This case shouldn't be given special handling at all--we're
721 // only supposed to drop the ".message_set_extension" for
722 // extensions defined within a message (i.e., the extension
723 // takes the message's name).
724 //
725 // This matches the behavior of the v1 generator, however.
726 //
727 // TODO: See if we can drop this case.
728 name = extension.Desc.FullName()
729 name = name[:len(name)-len("message_set_extension")]
730 return name, true
731 }
732 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700733}
734
Damien Neil993c04d2018-09-14 15:41:11 -0700735// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700736func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700737 name := "E_"
738 if extension.ParentMessage != nil {
739 name += extension.ParentMessage.GoIdent.GoName + "_"
740 }
741 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800742 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700743}
744
Damien Neilce36f8d2018-09-13 15:19:08 -0700745// genInitFunction generates an init function that registers the types in the
746// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700747func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neilce36f8d2018-09-13 15:19:08 -0700748 g.P("func init() {")
Joe Tsai9667c482018-12-05 15:42:52 -0800749 g.P(f.protoPackage().Ident("RegisterFile"), "(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ")")
Damien Neil154da982018-09-19 13:21:58 -0700750 for _, enum := range f.allEnums {
751 name := enum.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800752 g.P(f.protoPackage().Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700753 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700754 for _, message := range f.allMessages {
755 if message.Desc.IsMapEntry() {
756 continue
757 }
758
759 name := message.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800760 g.P(f.protoPackage().Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700761
762 // Types of map fields, sorted by the name of the field message type.
763 var mapFields []*protogen.Field
764 for _, field := range message.Fields {
765 if field.Desc.IsMap() {
766 mapFields = append(mapFields, field)
767 }
768 }
769 sort.Slice(mapFields, func(i, j int) bool {
770 ni := mapFields[i].MessageType.Desc.FullName()
771 nj := mapFields[j].MessageType.Desc.FullName()
772 return ni < nj
773 })
774 for _, field := range mapFields {
775 typeName := string(field.MessageType.Desc.FullName())
776 goType, _ := fieldGoType(g, field)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800777 g.P(f.protoPackage().Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700778 }
779 }
Joe Tsai9667c482018-12-05 15:42:52 -0800780 for _, extension := range f.allExtensions {
781 g.P(f.protoPackage().Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil993c04d2018-09-14 15:41:11 -0700782 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700783 g.P("}")
784 g.P()
785}
786
Damien Neil55fe1c02018-09-17 15:11:24 -0700787// deprecationComment returns a standard deprecation comment if deprecated is true.
788func deprecationComment(deprecated bool) string {
789 if !deprecated {
790 return ""
791 }
792 return "// Deprecated: Do not use."
793}
794
Damien Neilea7baf42018-09-28 14:23:44 -0700795func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700796 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700797 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700798 g.P()
799 }
800}
801
802// Names of messages and enums for which we will generate XXX_WellKnownType methods.
803var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700804 "google.protobuf.Any": true,
805 "google.protobuf.Duration": true,
806 "google.protobuf.Empty": true,
807 "google.protobuf.Struct": true,
808 "google.protobuf.Timestamp": true,
809
810 "google.protobuf.BoolValue": true,
811 "google.protobuf.BytesValue": true,
812 "google.protobuf.DoubleValue": true,
813 "google.protobuf.FloatValue": true,
814 "google.protobuf.Int32Value": true,
815 "google.protobuf.Int64Value": true,
816 "google.protobuf.ListValue": true,
817 "google.protobuf.NullValue": true,
818 "google.protobuf.StringValue": true,
819 "google.protobuf.UInt32Value": true,
820 "google.protobuf.UInt64Value": true,
821 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700822}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800823
824// genOneofField generates the struct field for a oneof.
825func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
826 if g.PrintLeadingComments(oneof.Location) {
827 g.P("//")
828 }
829 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
830 for _, field := range oneof.Fields {
831 g.PrintLeadingComments(field.Location)
832 g.P("//\t*", fieldOneofType(field))
833 }
834 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
835 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
836}
837
838// genOneofTypes generates the interface type used for a oneof field,
839// and the wrapper types that satisfy that interface.
840//
841// It also generates the getter method for the parent oneof field
842// (but not the member fields).
843func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
844 ifName := oneofInterfaceName(oneof)
845 g.P("type ", ifName, " interface {")
846 g.P(ifName, "()")
847 g.P("}")
848 g.P()
849 for _, field := range oneof.Fields {
850 name := fieldOneofType(field)
851 g.Annotate(name.GoName, field.Location)
852 g.Annotate(name.GoName+"."+field.GoName, field.Location)
853 g.P("type ", name, " struct {")
854 goType, _ := fieldGoType(g, field)
855 tags := []string{
856 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
857 }
858 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
859 g.P("}")
860 g.P()
861 }
862 for _, field := range oneof.Fields {
863 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
864 g.P()
865 }
866 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
867 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
868 g.P("if m != nil {")
869 g.P("return m.", oneofFieldName(oneof))
870 g.P("}")
871 g.P("return nil")
872 g.P("}")
873 g.P()
874}
875
876// oneofFieldName returns the name of the struct field holding the oneof value.
877//
878// This function is trivial, but pulling out the name like this makes it easier
879// to experiment with alternative oneof implementations.
880func oneofFieldName(oneof *protogen.Oneof) string {
881 return oneof.GoName
882}
883
884// oneofInterfaceName returns the name of the interface type implemented by
885// the oneof field value types.
886func oneofInterfaceName(oneof *protogen.Oneof) string {
887 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
888}
889
890// genOneofWrappers generates the XXX_OneofWrappers method for a message.
891func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
892 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
893 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
894 g.P("return []interface{}{")
895 for _, oneof := range message.Oneofs {
896 for _, field := range oneof.Fields {
897 g.P("(*", fieldOneofType(field), ")(nil),")
898 }
899 }
900 g.P("}")
901 g.P("}")
902 g.P()
903}
904
905// fieldOneofType returns the wrapper type used to represent a field in a oneof.
906func fieldOneofType(field *protogen.Field) protogen.GoIdent {
907 ident := protogen.GoIdent{
908 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
909 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
910 }
911 // Check for collisions with nested messages or enums.
912 //
913 // This conflict resolution is incomplete: Among other things, it
914 // does not consider collisions with other oneof field types.
915 //
916 // TODO: Consider dropping this entirely. Detecting conflicts and
917 // producing an error is almost certainly better than permuting
918 // field and type names in mostly unpredictable ways.
919Loop:
920 for {
921 for _, message := range field.ParentMessage.Messages {
922 if message.GoIdent == ident {
923 ident.GoName += "_"
924 continue Loop
925 }
926 }
927 for _, enum := range field.ParentMessage.Enums {
928 if enum.GoIdent == ident {
929 ident.GoName += "_"
930 continue Loop
931 }
932 }
933 return ident
934 }
935}