blob: f8312419e7076f1fa8c6bfb8e530568e48ecf036 [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 "fmt"
Damien Neil7bf3ce22018-12-21 15:54:06 -080010 "go/ast"
11 "go/parser"
12 "go/token"
Damien Neilebc699d2018-09-13 08:50:13 -070013 "math"
Damien Neil7779e052018-09-07 14:14:06 -070014 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070015 "strings"
Damien Neil7bf3ce22018-12-21 15:54:06 -080016 "unicode"
17 "unicode/utf8"
Damien Neil7779e052018-09-07 14:14:06 -070018
Joe Tsai05828db2018-11-01 13:52:16 -070019 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsaica46d8c2019-03-20 16:51:09 -070020 "github.com/golang/protobuf/v2/internal/fieldnum"
Joe Tsaif31bf262019-03-18 14:54:34 -070021 "github.com/golang/protobuf/v2/proto"
Joe Tsai01ab2962018-09-21 17:44:00 -070022 "github.com/golang/protobuf/v2/protogen"
23 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080024
25 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070026)
27
Joe Tsaic1c17aa2018-11-16 11:14:14 -080028const (
Joe Tsai4fddeba2019-03-20 18:29:32 -070029 mathPackage = protogen.GoImportPath("math")
Joe Tsai4fddeba2019-03-20 18:29:32 -070030 protoifacePackage = protogen.GoImportPath("github.com/golang/protobuf/v2/runtime/protoiface")
31 protoimplPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/runtime/protoimpl")
32 protoreflectPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/reflect/protoreflect")
33 protoregistryPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/reflect/protoregistry")
34 prototypePackage = protogen.GoImportPath("github.com/golang/protobuf/v2/internal/prototype")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080035)
Damien Neil46abb572018-09-07 12:45:37 -070036
Damien Neild39efc82018-09-24 12:38:10 -070037type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070038 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080039
40 // vars containing the raw wire-encoded and compressed FileDescriptorProto.
41 descriptorRawVar string
42 descriptorGzipVar string
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
Damien Neil9c420a62018-09-27 15:26:33 -070051// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080052func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
53 filename := file.GeneratedFilenamePrefix + ".pb.go"
54 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070055 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070056 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070057 }
58
Damien Neil8012b442019-01-18 09:32:24 -080059 // Collect all enums, messages, and extensions in "flattened ordering".
60 // See fileinit.FileBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080061 f.allEnums = append(f.allEnums, f.Enums...)
62 f.allMessages = append(f.allMessages, f.Messages...)
63 f.allExtensions = append(f.allExtensions, f.Extensions...)
64 walkMessages(f.Messages, func(m *protogen.Message) {
65 f.allEnums = append(f.allEnums, m.Enums...)
66 f.allMessages = append(f.allMessages, m.Messages...)
67 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070068 })
Damien Neilce36f8d2018-09-13 15:19:08 -070069
Joe Tsai9667c482018-12-05 15:42:52 -080070 // Derive a reverse mapping of enum and message pointers to their index
71 // in allEnums and allMessages.
72 if len(f.allEnums) > 0 {
73 f.allEnumsByPtr = make(map[*protogen.Enum]int)
74 for i, e := range f.allEnums {
75 f.allEnumsByPtr[e] = i
76 }
77 }
78 if len(f.allMessages) > 0 {
79 f.allMessagesByPtr = make(map[*protogen.Message]int)
80 for i, m := range f.allMessages {
81 f.allMessagesByPtr[m] = i
82 }
83 }
Joe Tsaib6405bd2018-11-15 14:44:37 -080084
Joe Tsai40692112019-02-27 20:25:51 -080085 // Determine the name of the var holding the file descriptor.
86 f.descriptorRawVar = "xxx_" + f.GoDescriptorIdent.GoName + "_rawdesc"
Damien Neil8012b442019-01-18 09:32:24 -080087 f.descriptorGzipVar = f.descriptorRawVar + "_gzipped"
Damien Neil46abb572018-09-07 12:45:37 -070088
Damien Neil220c2022018-08-15 11:24:18 -070089 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070090 if f.Proto.GetOptions().GetDeprecated() {
91 g.P("// ", f.Desc.Path(), " is a deprecated file.")
92 } else {
93 g.P("// source: ", f.Desc.Path())
94 }
Damien Neil220c2022018-08-15 11:24:18 -070095 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -070096 g.PrintLeadingComments(protogen.Location{
97 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -070098 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -070099 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700100 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700101 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700102 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700103
Damien Neil73ac8852018-09-17 15:11:24 -0700104 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
105 genImport(gen, g, f, imps.Get(i))
106 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700107 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700108 genEnum(gen, g, f, enum)
109 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700110 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700111 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700112 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700113 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700114
Damien Neil7779e052018-09-07 14:14:06 -0700115 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800116 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800117
118 return g
Damien Neil7779e052018-09-07 14:14:06 -0700119}
120
Damien Neil73ac8852018-09-17 15:11:24 -0700121// walkMessages calls f on each message and all of its descendants.
122func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
123 for _, m := range messages {
124 f(m)
125 walkMessages(m.Messages, f)
126 }
127}
128
Damien Neild39efc82018-09-24 12:38:10 -0700129func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700130 impFile, ok := gen.FileByName(imp.Path())
131 if !ok {
132 return
133 }
134 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700135 // Don't generate imports or aliases for types in the same Go package.
136 return
137 }
Damien Neil40a08052018-10-29 09:07:41 -0700138 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700139 // referenced, because other code and tools depend on having the
140 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700141 if !imp.IsWeak {
142 g.Import(impFile.GoImportPath)
143 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700144 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700145 return
146 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800147
148 // Generate public imports by generating the imported file, parsing it,
149 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800150 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800151 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800152 b, err := impGen.Content()
153 if err != nil {
154 gen.Error(err)
155 return
156 }
157 fset := token.NewFileSet()
158 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
159 if err != nil {
160 gen.Error(err)
161 return
162 }
Damien Neila7cbd062019-01-06 16:29:14 -0800163 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800164 // Don't import unexported symbols.
165 r, _ := utf8.DecodeRuneInString(name)
166 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700167 return
168 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800169 // Don't import the FileDescriptor.
170 if name == impFile.GoDescriptorIdent.GoName {
171 return
172 }
Damien Neila7cbd062019-01-06 16:29:14 -0800173 // Don't import decls referencing a symbol defined in another package.
174 // i.e., don't import decls which are themselves public imports:
175 //
176 // type T = somepackage.T
177 if _, ok := expr.(*ast.SelectorExpr); ok {
178 return
179 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800180 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
181 }
182 g.P("// Symbols defined in public import of ", imp.Path())
183 g.P()
184 for _, decl := range astFile.Decls {
185 switch decl := decl.(type) {
186 case *ast.GenDecl:
187 for _, spec := range decl.Specs {
188 switch spec := spec.(type) {
189 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800190 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800191 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800192 for i, name := range spec.Names {
193 var expr ast.Expr
194 if i < len(spec.Values) {
195 expr = spec.Values[i]
196 }
197 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800198 }
199 case *ast.ImportSpec:
200 default:
201 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800202 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700203 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700204 }
Damien Neil6b541312018-10-29 09:14:14 -0700205 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700206 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700207}
208
Damien Neild39efc82018-09-24 12:38:10 -0700209func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Joe Tsaif31bf262019-03-18 14:54:34 -0700210 // TODO: Replace this with v2 Clone.
211 descProto := new(descriptorpb.FileDescriptorProto)
212 b, err := proto.Marshal(f.Proto)
213 if err != nil {
214 gen.Error(err)
215 return
216 }
217 if err := proto.Unmarshal(b, descProto); err != nil {
218 gen.Error(err)
219 return
220 }
221
Damien Neil7779e052018-09-07 14:14:06 -0700222 // Trim the source_code_info from the descriptor.
Damien Neil7779e052018-09-07 14:14:06 -0700223 descProto.SourceCodeInfo = nil
Joe Tsaif31bf262019-03-18 14:54:34 -0700224 b, err = proto.MarshalOptions{Deterministic: true}.Marshal(descProto)
Damien Neil7779e052018-09-07 14:14:06 -0700225 if err != nil {
226 gen.Error(err)
227 return
228 }
Damien Neil7779e052018-09-07 14:14:06 -0700229
Damien Neil8012b442019-01-18 09:32:24 -0800230 g.P("var ", f.descriptorRawVar, " = []byte{")
231 g.P("// ", len(b), " bytes of the wire-encoded FileDescriptorProto")
Damien Neil7779e052018-09-07 14:14:06 -0700232 for len(b) > 0 {
233 n := 16
234 if n > len(b) {
235 n = len(b)
236 }
237
238 s := ""
239 for _, c := range b[:n] {
240 s += fmt.Sprintf("0x%02x,", c)
241 }
242 g.P(s)
243
244 b = b[n:]
245 }
246 g.P("}")
247 g.P()
Damien Neil8012b442019-01-18 09:32:24 -0800248
Joe Tsaicf81e672019-02-28 14:08:31 -0800249 // TODO: Modify CompressGZIP to lazy encode? Currently, the GZIP'd form
250 // is eagerly registered in v1, preventing any benefit from lazy encoding.
Joe Tsai8e506a82019-03-16 00:05:34 -0700251 g.P("var ", f.descriptorGzipVar, " = ", protoimplPackage.Ident("X"), ".CompressGZIP(", f.descriptorRawVar, ")")
Damien Neil8012b442019-01-18 09:32:24 -0800252 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700253}
Damien Neilc7d07d92018-08-22 13:46:02 -0700254
Damien Neild39efc82018-09-24 12:38:10 -0700255func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700256 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700257 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700258 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800259 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700260 g.P("const (")
261 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700262 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700263 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700264 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800265 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700266 }
267 g.P(")")
268 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800269
270 // Generate support for protobuf reflection.
271 genReflectEnum(gen, g, f, enum)
272
Damien Neil46abb572018-09-07 12:45:37 -0700273 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsai8e506a82019-03-16 00:05:34 -0700274 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700275 g.P("var ", nameMap, " = map[int32]string{")
276 generated := make(map[protoreflect.EnumNumber]bool)
277 for _, value := range enum.Values {
278 duplicate := ""
279 if _, present := generated[value.Desc.Number()]; present {
280 duplicate = "// Duplicate value: "
281 }
282 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
283 generated[value.Desc.Number()] = true
284 }
285 g.P("}")
286 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700287
Damien Neil46abb572018-09-07 12:45:37 -0700288 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsai8e506a82019-03-16 00:05:34 -0700289 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700290 g.P("var ", valueMap, " = map[string]int32{")
291 for _, value := range enum.Values {
292 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
293 }
294 g.P("}")
295 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700296
Damien Neil46abb572018-09-07 12:45:37 -0700297 if enum.Desc.Syntax() != protoreflect.Proto3 {
298 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700299 g.P("return &x")
Damien Neil46abb572018-09-07 12:45:37 -0700300 g.P("}")
301 g.P()
302 }
303 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700304 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Type(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700305 g.P("}")
306 g.P()
307
Joe Tsai73903462018-12-14 12:22:41 -0800308 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700309 g.P("// Deprecated: Do not use.")
310 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
311 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Type(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700312 g.P("if err != nil {")
313 g.P("return err")
314 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700315 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700316 g.P("return nil")
317 g.P("}")
318 g.P()
319 }
320
321 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700322 for i := 1; i < len(enum.Location.Path); i += 2 {
323 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700324 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700325 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700326 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800327 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neil46abb572018-09-07 12:45:37 -0700328 g.P("}")
329 g.P()
330
Damien Neilea7baf42018-09-28 14:23:44 -0700331 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700332}
333
Damien Neil658051b2018-09-10 12:26:21 -0700334// enumRegistryName returns the name used to register an enum with the proto
335// package registry.
336//
337// Confusingly, this is <proto_package>.<go_ident>. This probably should have
338// been the full name of the proto enum type instead, but changing it at this
339// point would require thought.
340func enumRegistryName(enum *protogen.Enum) string {
341 // Find the FileDescriptor for this enum.
342 var desc protoreflect.Descriptor = enum.Desc
343 for {
344 p, ok := desc.Parent()
345 if !ok {
346 break
347 }
348 desc = p
349 }
350 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700351 if fdesc.Package() == "" {
352 return enum.GoIdent.GoName
353 }
Damien Neil658051b2018-09-10 12:26:21 -0700354 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
355}
356
Damien Neild39efc82018-09-24 12:38:10 -0700357func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700358 if message.Desc.IsMapEntry() {
359 return
360 }
361
Damien Neilba1159f2018-10-17 12:53:18 -0700362 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800363 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700364 if hasComment {
365 g.P("//")
366 }
367 g.P(deprecationComment(true))
368 }
Damien Neil162c1272018-10-04 12:42:37 -0700369 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700370 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700371 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700372 if field.OneofType != nil {
373 // It would be a bit simpler to iterate over the oneofs below,
374 // but generating the field here keeps the contents of the Go
375 // struct in the same order as the contents of the source
376 // .proto file.
377 if field == field.OneofType.Fields[0] {
378 genOneofField(gen, g, f, message, field.OneofType)
379 }
Damien Neil658051b2018-09-10 12:26:21 -0700380 continue
381 }
Damien Neilba1159f2018-10-17 12:53:18 -0700382 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700383 goType, pointer := fieldGoType(g, field)
384 if pointer {
385 goType = "*" + goType
386 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700387 tags := []string{
388 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
389 fmt.Sprintf("json:%q", fieldJSONTag(field)),
390 }
391 if field.Desc.IsMap() {
392 key := field.MessageType.Fields[0]
393 val := field.MessageType.Fields[1]
394 tags = append(tags,
395 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
396 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
397 )
398 }
Damien Neil162c1272018-10-04 12:42:37 -0700399 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700400 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800401 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700402 }
403 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700404
405 if message.Desc.ExtensionRanges().Len() > 0 {
406 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800407 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700408 tags = append(tags, `protobuf_messageset:"1"`)
409 }
410 tags = append(tags, `json:"-"`)
Joe Tsai4fddeba2019-03-20 18:29:32 -0700411 g.P("XXX_InternalExtensions ", protoimplPackage.Ident("ExtensionFieldsV1"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700412 }
Damien Neil658051b2018-09-10 12:26:21 -0700413 g.P("XXX_unrecognized []byte `json:\"-\"`")
414 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700415 g.P("}")
416 g.P()
417
Joe Tsaib6405bd2018-11-15 14:44:37 -0800418 // Generate support for protobuf reflection.
419 genReflectMessage(gen, g, f, message)
420
Damien Neila1c6abc2018-09-12 13:36:34 -0700421 // Reset
422 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
423 // String
Joe Tsai35ec98f2019-03-25 14:41:32 -0700424 g.P("func (m *", message.GoIdent, ") String() string { return ", protoimplPackage.Ident("X"), ".MessageStringOf(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700425 // ProtoMessage
426 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
427 // Descriptor
428 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700429 for i := 1; i < len(message.Location.Path); i += 2 {
430 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700431 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700432 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
Damien Neila1c6abc2018-09-12 13:36:34 -0700433 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800434 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neila1c6abc2018-09-12 13:36:34 -0700435 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700436 g.P()
437
438 // ExtensionRangeArray
439 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700440 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700441 extRangeVar := "extRange_" + message.GoIdent.GoName
442 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
443 for i := 0; i < extranges.Len(); i++ {
444 r := extranges.Get(i)
445 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
446 }
447 g.P("}")
448 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700449 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700450 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
451 g.P("return ", extRangeVar)
452 g.P("}")
453 g.P()
454 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700455
Damien Neilea7baf42018-09-28 14:23:44 -0700456 genWellKnownType(g, "*", message.GoIdent, message.Desc)
457
Damien Neilebc699d2018-09-13 08:50:13 -0700458 // Constants and vars holding the default values of fields.
459 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800460 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700461 continue
462 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700463 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700464 def := field.Desc.Default()
465 switch field.Desc.Kind() {
466 case protoreflect.StringKind:
467 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
468 case protoreflect.BytesKind:
469 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
470 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700471 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700472 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700473 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700474 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
475 case protoreflect.FloatKind, protoreflect.DoubleKind:
476 // Floating point numbers need extra handling for -Inf/Inf/NaN.
477 f := field.Desc.Default().Float()
478 goType := "float64"
479 if field.Desc.Kind() == protoreflect.FloatKind {
480 goType = "float32"
481 }
482 // funcCall returns a call to a function in the math package,
483 // possibly converting the result to float32.
484 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800485 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700486 if goType != "float64" {
487 s = goType + "(" + s + ")"
488 }
489 return s
490 }
491 switch {
492 case math.IsInf(f, -1):
493 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
494 case math.IsInf(f, 1):
495 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
496 case math.IsNaN(f):
497 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
498 default:
Damien Neil982684b2018-09-28 14:12:41 -0700499 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700500 }
501 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700502 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700503 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
504 }
505 }
506 g.P()
507
Damien Neil77f82fe2018-09-13 10:59:17 -0700508 // Getters.
509 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700510 if field.OneofType != nil {
511 if field == field.OneofType.Fields[0] {
512 genOneofTypes(gen, g, f, message, field.OneofType)
513 }
514 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700515 goType, pointer := fieldGoType(g, field)
516 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800517 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700518 g.P(deprecationComment(true))
519 }
Damien Neil162c1272018-10-04 12:42:37 -0700520 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700521 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
522 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700523 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700524 g.P("return x.", field.GoName)
525 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700526 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700527 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
528 g.P("if m != nil {")
529 } else {
530 g.P("if m != nil && m.", field.GoName, " != nil {")
531 }
532 star := ""
533 if pointer {
534 star = "*"
535 }
536 g.P("return ", star, " m.", field.GoName)
537 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700538 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700539 g.P("return ", defaultValue)
540 g.P("}")
541 g.P()
542 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700543
Damien Neil1fa78d82018-09-13 13:12:36 -0700544 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800545 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700546 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700547}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700548
Damien Neil77f82fe2018-09-13 10:59:17 -0700549// fieldGoType returns the Go type used for a field.
550//
551// If it returns pointer=true, the struct field is a pointer to the type.
552func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700553 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700554 switch field.Desc.Kind() {
555 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700556 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700557 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700558 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700559 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700560 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700561 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700562 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700563 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700564 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700565 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700566 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700567 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700568 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700569 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700570 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700571 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700572 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700573 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700574 goType = "[]byte"
575 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700576 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700577 if field.Desc.IsMap() {
578 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
579 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
580 return fmt.Sprintf("map[%v]%v", keyType, valType), false
581 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700582 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
583 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700584 }
585 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700586 goType = "[]" + goType
587 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700588 }
Damien Neil44000a12018-10-24 12:31:16 -0700589 // Extension fields always have pointer type, even when defined in a proto3 file.
590 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700591 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700592 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700593 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700594}
595
596func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700597 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700598 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700599 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700600 }
Joe Tsai05828db2018-11-01 13:52:16 -0700601 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700602}
603
Damien Neil77f82fe2018-09-13 10:59:17 -0700604func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
605 if field.Desc.Cardinality() == protoreflect.Repeated {
606 return "nil"
607 }
Joe Tsai9667c482018-12-05 15:42:52 -0800608 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700609 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700610 if field.Desc.Kind() == protoreflect.BytesKind {
611 return "append([]byte(nil), " + defVarName + "...)"
612 }
613 return defVarName
614 }
615 switch field.Desc.Kind() {
616 case protoreflect.BoolKind:
617 return "false"
618 case protoreflect.StringKind:
619 return `""`
620 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
621 return "nil"
622 case protoreflect.EnumKind:
623 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
624 default:
625 return "0"
626 }
627}
628
Damien Neil658051b2018-09-10 12:26:21 -0700629func fieldJSONTag(field *protogen.Field) string {
630 return string(field.Desc.Name()) + ",omitempty"
631}
632
Joe Tsaiafb455e2019-03-14 16:08:22 -0700633func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
634 if len(f.allExtensions) == 0 {
635 return
Damien Neil154da982018-09-19 13:21:58 -0700636 }
637
Joe Tsai4fddeba2019-03-20 18:29:32 -0700638 g.P("var ", extDecsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700639 for _, extension := range f.allExtensions {
640 // Special case for proto2 message sets: If this extension is extending
641 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
642 // then drop that last component.
643 //
644 // TODO: This should be implemented in the text formatter rather than the generator.
645 // In addition, the situation for when to apply this special case is implemented
646 // differently in other languages:
647 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
648 name := extension.Desc.FullName()
649 if n, ok := isExtensionMessageSetElement(extension); ok {
650 name = n
651 }
652
653 g.P("{")
654 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
655 goType, pointer := fieldGoType(g, extension)
656 if pointer {
657 goType = "*" + goType
658 }
659 g.P("ExtensionType: (", goType, ")(nil),")
660 g.P("Field: ", extension.Desc.Number(), ",")
661 g.P("Name: ", strconv.Quote(string(name)), ",")
662 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
663 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
664 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700665 }
Damien Neil993c04d2018-09-14 15:41:11 -0700666 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700667
668 g.P("var (")
669 for i, extension := range f.allExtensions {
670 ed := extension.Desc
671 targetName := string(ed.ExtendedType().FullName())
672 typeName := ed.Kind().String()
673 switch ed.Kind() {
674 case protoreflect.EnumKind:
675 typeName = string(ed.EnumType().FullName())
676 case protoreflect.MessageKind, protoreflect.GroupKind:
677 typeName = string(ed.MessageType().FullName())
678 }
679 fieldName := string(ed.Name())
680 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
681 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
682 g.P()
683 }
684 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700685}
686
Damien Neil62386962018-10-30 10:35:48 -0700687// isExtensionMessageSetELement returns the adjusted name of an extension
688// which extends proto2.bridge.MessageSet.
689func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800690 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700691 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
692 return "", false
693 }
694 if extension.ParentMessage == nil {
695 // This case shouldn't be given special handling at all--we're
696 // only supposed to drop the ".message_set_extension" for
697 // extensions defined within a message (i.e., the extension
698 // takes the message's name).
699 //
700 // This matches the behavior of the v1 generator, however.
701 //
702 // TODO: See if we can drop this case.
703 name = extension.Desc.FullName()
704 name = name[:len(name)-len("message_set_extension")]
705 return name, true
706 }
707 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700708}
709
Damien Neil993c04d2018-09-14 15:41:11 -0700710// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700711func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700712 name := "E_"
713 if extension.ParentMessage != nil {
714 name += extension.ParentMessage.GoIdent.GoName + "_"
715 }
716 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800717 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700718}
719
Damien Neil55fe1c02018-09-17 15:11:24 -0700720// deprecationComment returns a standard deprecation comment if deprecated is true.
721func deprecationComment(deprecated bool) string {
722 if !deprecated {
723 return ""
724 }
725 return "// Deprecated: Do not use."
726}
727
Damien Neilea7baf42018-09-28 14:23:44 -0700728func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700729 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700730 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700731 g.P()
732 }
733}
734
735// Names of messages and enums for which we will generate XXX_WellKnownType methods.
736var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700737 "google.protobuf.Any": true,
738 "google.protobuf.Duration": true,
739 "google.protobuf.Empty": true,
740 "google.protobuf.Struct": true,
741 "google.protobuf.Timestamp": true,
742
743 "google.protobuf.BoolValue": true,
744 "google.protobuf.BytesValue": true,
745 "google.protobuf.DoubleValue": true,
746 "google.protobuf.FloatValue": true,
747 "google.protobuf.Int32Value": true,
748 "google.protobuf.Int64Value": true,
749 "google.protobuf.ListValue": true,
750 "google.protobuf.NullValue": true,
751 "google.protobuf.StringValue": true,
752 "google.protobuf.UInt32Value": true,
753 "google.protobuf.UInt64Value": true,
754 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700755}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800756
757// genOneofField generates the struct field for a oneof.
758func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
759 if g.PrintLeadingComments(oneof.Location) {
760 g.P("//")
761 }
762 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
763 for _, field := range oneof.Fields {
764 g.PrintLeadingComments(field.Location)
765 g.P("//\t*", fieldOneofType(field))
766 }
767 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
768 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
769}
770
771// genOneofTypes generates the interface type used for a oneof field,
772// and the wrapper types that satisfy that interface.
773//
774// It also generates the getter method for the parent oneof field
775// (but not the member fields).
776func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
777 ifName := oneofInterfaceName(oneof)
778 g.P("type ", ifName, " interface {")
779 g.P(ifName, "()")
780 g.P("}")
781 g.P()
782 for _, field := range oneof.Fields {
783 name := fieldOneofType(field)
784 g.Annotate(name.GoName, field.Location)
785 g.Annotate(name.GoName+"."+field.GoName, field.Location)
786 g.P("type ", name, " struct {")
787 goType, _ := fieldGoType(g, field)
788 tags := []string{
789 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
790 }
791 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
792 g.P("}")
793 g.P()
794 }
795 for _, field := range oneof.Fields {
796 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
797 g.P()
798 }
799 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
800 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
801 g.P("if m != nil {")
802 g.P("return m.", oneofFieldName(oneof))
803 g.P("}")
804 g.P("return nil")
805 g.P("}")
806 g.P()
807}
808
809// oneofFieldName returns the name of the struct field holding the oneof value.
810//
811// This function is trivial, but pulling out the name like this makes it easier
812// to experiment with alternative oneof implementations.
813func oneofFieldName(oneof *protogen.Oneof) string {
814 return oneof.GoName
815}
816
817// oneofInterfaceName returns the name of the interface type implemented by
818// the oneof field value types.
819func oneofInterfaceName(oneof *protogen.Oneof) string {
820 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
821}
822
823// genOneofWrappers generates the XXX_OneofWrappers method for a message.
824func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
825 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
826 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
827 g.P("return []interface{}{")
828 for _, oneof := range message.Oneofs {
829 for _, field := range oneof.Fields {
830 g.P("(*", fieldOneofType(field), ")(nil),")
831 }
832 }
833 g.P("}")
834 g.P("}")
835 g.P()
836}
837
838// fieldOneofType returns the wrapper type used to represent a field in a oneof.
839func fieldOneofType(field *protogen.Field) protogen.GoIdent {
840 ident := protogen.GoIdent{
841 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
842 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
843 }
844 // Check for collisions with nested messages or enums.
845 //
846 // This conflict resolution is incomplete: Among other things, it
847 // does not consider collisions with other oneof field types.
848 //
849 // TODO: Consider dropping this entirely. Detecting conflicts and
850 // producing an error is almost certainly better than permuting
851 // field and type names in mostly unpredictable ways.
852Loop:
853 for {
854 for _, message := range field.ParentMessage.Messages {
855 if message.GoIdent == ident {
856 ident.GoName += "_"
857 continue Loop
858 }
859 }
860 for _, enum := range field.ParentMessage.Enums {
861 if enum.GoIdent == ident {
862 ident.GoName += "_"
863 continue Loop
864 }
865 }
866 return ident
867 }
868}