blob: 1b8b332f1236fe9629ef69f1019926d5e836aa9e [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 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
Joe Tsai5d72cc22019-03-28 01:13:26 -070027// minimumVersion is minimum version of the v2 proto package that is required.
28// This is incremented every time the generated code relies on some property
29// in the proto package that was introduced in a later version.
30const minimumVersion = 0
31
Joe Tsaic1c17aa2018-11-16 11:14:14 -080032const (
Joe Tsai5d72cc22019-03-28 01:13:26 -070033 syncPackage = protogen.GoImportPath("sync")
Joe Tsai4fddeba2019-03-20 18:29:32 -070034 mathPackage = protogen.GoImportPath("math")
Joe Tsai4fddeba2019-03-20 18:29:32 -070035 protoifacePackage = protogen.GoImportPath("github.com/golang/protobuf/v2/runtime/protoiface")
36 protoimplPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/runtime/protoimpl")
37 protoreflectPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/reflect/protoreflect")
38 protoregistryPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/reflect/protoregistry")
39 prototypePackage = protogen.GoImportPath("github.com/golang/protobuf/v2/internal/prototype")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080040)
Damien Neil46abb572018-09-07 12:45:37 -070041
Damien Neild39efc82018-09-24 12:38:10 -070042type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070043 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080044
Joe Tsai9667c482018-12-05 15:42:52 -080045 allEnums []*protogen.Enum
46 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
47 allMessages []*protogen.Message
48 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
49 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070050}
51
Damien Neil9c420a62018-09-27 15:26:33 -070052// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080053func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
54 filename := file.GeneratedFilenamePrefix + ".pb.go"
55 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070056 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070057 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070058 }
59
Damien Neil8012b442019-01-18 09:32:24 -080060 // Collect all enums, messages, and extensions in "flattened ordering".
61 // See fileinit.FileBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080062 f.allEnums = append(f.allEnums, f.Enums...)
63 f.allMessages = append(f.allMessages, f.Messages...)
64 f.allExtensions = append(f.allExtensions, f.Extensions...)
65 walkMessages(f.Messages, func(m *protogen.Message) {
66 f.allEnums = append(f.allEnums, m.Enums...)
67 f.allMessages = append(f.allMessages, m.Messages...)
68 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070069 })
Damien Neilce36f8d2018-09-13 15:19:08 -070070
Joe Tsai9667c482018-12-05 15:42:52 -080071 // Derive a reverse mapping of enum and message pointers to their index
72 // in allEnums and allMessages.
73 if len(f.allEnums) > 0 {
74 f.allEnumsByPtr = make(map[*protogen.Enum]int)
75 for i, e := range f.allEnums {
76 f.allEnumsByPtr[e] = i
77 }
78 }
79 if len(f.allMessages) > 0 {
80 f.allMessagesByPtr = make(map[*protogen.Message]int)
81 for i, m := range f.allMessages {
82 f.allMessagesByPtr[m] = i
83 }
84 }
Joe Tsaib6405bd2018-11-15 14:44:37 -080085
Damien Neil220c2022018-08-15 11:24:18 -070086 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070087 if f.Proto.GetOptions().GetDeprecated() {
88 g.P("// ", f.Desc.Path(), " is a deprecated file.")
89 } else {
90 g.P("// source: ", f.Desc.Path())
91 }
Damien Neil220c2022018-08-15 11:24:18 -070092 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -070093 g.PrintLeadingComments(protogen.Location{
94 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -070095 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -070096 })
Damien Neilcab8dfe2018-09-06 14:51:28 -070097 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070098 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070099 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700100
Joe Tsai5d72cc22019-03-28 01:13:26 -0700101 // Emit a static check that enforces a minimum version of the proto package.
102 g.P("const _ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("Version"), " - ", minimumVersion, ")")
103 g.P()
104
Damien Neil73ac8852018-09-17 15:11:24 -0700105 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
106 genImport(gen, g, f, imps.Get(i))
107 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700108 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700109 genEnum(gen, g, f, enum)
110 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700111 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700112 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700113 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700114 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700115
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 genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Joe Tsai61968ce2019-04-01 12:59:24 -0700210 // Enum type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700211 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700212 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700213 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800214 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Joe Tsai61968ce2019-04-01 12:59:24 -0700215
216 // Enum value constants.
Damien Neil46abb572018-09-07 12:45:37 -0700217 g.P("const (")
218 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700219 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700220 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700221 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800222 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700223 }
224 g.P(")")
225 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800226
Joe Tsai61968ce2019-04-01 12:59:24 -0700227 // Enum value mapping (number -> name).
Damien Neil46abb572018-09-07 12:45:37 -0700228 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsai8e506a82019-03-16 00:05:34 -0700229 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700230 g.P("var ", nameMap, " = map[int32]string{")
231 generated := make(map[protoreflect.EnumNumber]bool)
232 for _, value := range enum.Values {
233 duplicate := ""
234 if _, present := generated[value.Desc.Number()]; present {
235 duplicate = "// Duplicate value: "
236 }
237 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
238 generated[value.Desc.Number()] = true
239 }
240 g.P("}")
241 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700242
Joe Tsai61968ce2019-04-01 12:59:24 -0700243 // Enum value mapping (name -> number).
Damien Neil46abb572018-09-07 12:45:37 -0700244 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsai8e506a82019-03-16 00:05:34 -0700245 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700246 g.P("var ", valueMap, " = map[string]int32{")
247 for _, value := range enum.Values {
248 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
249 }
250 g.P("}")
251 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700252
Joe Tsai61968ce2019-04-01 12:59:24 -0700253 // Enum method.
Damien Neil46abb572018-09-07 12:45:37 -0700254 if enum.Desc.Syntax() != protoreflect.Proto3 {
255 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700256 g.P("return &x")
Damien Neil46abb572018-09-07 12:45:37 -0700257 g.P("}")
258 g.P()
259 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700260 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700261 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700262 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Type(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700263 g.P("}")
264 g.P()
265
Joe Tsai61968ce2019-04-01 12:59:24 -0700266 genReflectEnum(gen, g, f, enum)
267
268 // UnmarshalJSON method.
Joe Tsai73903462018-12-14 12:22:41 -0800269 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700270 g.P("// Deprecated: Do not use.")
271 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
272 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Type(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700273 g.P("if err != nil {")
274 g.P("return err")
275 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700276 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700277 g.P("return nil")
278 g.P("}")
279 g.P()
280 }
281
Joe Tsai61968ce2019-04-01 12:59:24 -0700282 // EnumDescriptor method.
Damien Neil46abb572018-09-07 12:45:37 -0700283 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700284 for i := 1; i < len(enum.Location.Path); i += 2 {
285 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700286 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700287 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700288 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
Joe Tsai5d72cc22019-03-28 01:13:26 -0700289 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
Damien Neil46abb572018-09-07 12:45:37 -0700290 g.P("}")
291 g.P()
292
Damien Neilea7baf42018-09-28 14:23:44 -0700293 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700294}
295
Joe Tsai61968ce2019-04-01 12:59:24 -0700296// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700297//
298// Confusingly, this is <proto_package>.<go_ident>. This probably should have
299// been the full name of the proto enum type instead, but changing it at this
300// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700301func enumLegacyName(enum *protogen.Enum) string {
Damien Neil658051b2018-09-10 12:26:21 -0700302 // Find the FileDescriptor for this enum.
303 var desc protoreflect.Descriptor = enum.Desc
304 for {
305 p, ok := desc.Parent()
306 if !ok {
307 break
308 }
309 desc = p
310 }
311 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700312 if fdesc.Package() == "" {
313 return enum.GoIdent.GoName
314 }
Damien Neil658051b2018-09-10 12:26:21 -0700315 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
316}
317
Damien Neild39efc82018-09-24 12:38:10 -0700318func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700319 if message.Desc.IsMapEntry() {
320 return
321 }
322
Joe Tsai61968ce2019-04-01 12:59:24 -0700323 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700324 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800325 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700326 if hasComment {
327 g.P("//")
328 }
329 g.P(deprecationComment(true))
330 }
Damien Neil162c1272018-10-04 12:42:37 -0700331 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700332 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700333 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700334 if field.OneofType != nil {
335 // It would be a bit simpler to iterate over the oneofs below,
336 // but generating the field here keeps the contents of the Go
337 // struct in the same order as the contents of the source
338 // .proto file.
339 if field == field.OneofType.Fields[0] {
340 genOneofField(gen, g, f, message, field.OneofType)
341 }
Damien Neil658051b2018-09-10 12:26:21 -0700342 continue
343 }
Damien Neilba1159f2018-10-17 12:53:18 -0700344 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700345 goType, pointer := fieldGoType(g, field)
346 if pointer {
347 goType = "*" + goType
348 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700349 tags := []string{
350 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
351 fmt.Sprintf("json:%q", fieldJSONTag(field)),
352 }
353 if field.Desc.IsMap() {
354 key := field.MessageType.Fields[0]
355 val := field.MessageType.Fields[1]
356 tags = append(tags,
357 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
358 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
359 )
360 }
Damien Neil162c1272018-10-04 12:42:37 -0700361 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700362 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800363 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700364 }
365 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700366
367 if message.Desc.ExtensionRanges().Len() > 0 {
368 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800369 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700370 tags = append(tags, `protobuf_messageset:"1"`)
371 }
372 tags = append(tags, `json:"-"`)
Joe Tsai4fddeba2019-03-20 18:29:32 -0700373 g.P("XXX_InternalExtensions ", protoimplPackage.Ident("ExtensionFieldsV1"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700374 }
Damien Neil658051b2018-09-10 12:26:21 -0700375 g.P("XXX_unrecognized []byte `json:\"-\"`")
376 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700377 g.P("}")
378 g.P()
379
Joe Tsai61968ce2019-04-01 12:59:24 -0700380 // Reset method.
381 g.P("func (x *", message.GoIdent, ") Reset() {")
382 g.P("*x = ", message.GoIdent, "{}")
383 g.P("}")
384 g.P()
385 // String method.
386 g.P("func (x *", message.GoIdent, ") String() string {")
387 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
388 g.P("}")
389 g.P()
390 // ProtoMessage method.
391 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
392 g.P()
393
Joe Tsaib6405bd2018-11-15 14:44:37 -0800394 genReflectMessage(gen, g, f, message)
395
Joe Tsai61968ce2019-04-01 12:59:24 -0700396 // Descriptor method.
Damien Neila1c6abc2018-09-12 13:36:34 -0700397 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700398 for i := 1; i < len(message.Location.Path); i += 2 {
399 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700400 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700401 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
Damien Neila1c6abc2018-09-12 13:36:34 -0700402 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
Joe Tsai5d72cc22019-03-28 01:13:26 -0700403 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
Damien Neila1c6abc2018-09-12 13:36:34 -0700404 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700405 g.P()
406
Joe Tsai61968ce2019-04-01 12:59:24 -0700407 // ExtensionRangeArray method.
Damien Neil993c04d2018-09-14 15:41:11 -0700408 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700409 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700410 extRangeVar := "extRange_" + message.GoIdent.GoName
411 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
412 for i := 0; i < extranges.Len(); i++ {
413 r := extranges.Get(i)
414 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
415 }
416 g.P("}")
417 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700418 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700419 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
420 g.P("return ", extRangeVar)
421 g.P("}")
422 g.P()
423 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700424
Damien Neilea7baf42018-09-28 14:23:44 -0700425 genWellKnownType(g, "*", message.GoIdent, message.Desc)
426
Damien Neilebc699d2018-09-13 08:50:13 -0700427 // Constants and vars holding the default values of fields.
428 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800429 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700430 continue
431 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700432 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700433 def := field.Desc.Default()
434 switch field.Desc.Kind() {
435 case protoreflect.StringKind:
436 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
437 case protoreflect.BytesKind:
438 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
439 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700440 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700441 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700442 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700443 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
444 case protoreflect.FloatKind, protoreflect.DoubleKind:
445 // Floating point numbers need extra handling for -Inf/Inf/NaN.
446 f := field.Desc.Default().Float()
447 goType := "float64"
448 if field.Desc.Kind() == protoreflect.FloatKind {
449 goType = "float32"
450 }
451 // funcCall returns a call to a function in the math package,
452 // possibly converting the result to float32.
453 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800454 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700455 if goType != "float64" {
456 s = goType + "(" + s + ")"
457 }
458 return s
459 }
460 switch {
461 case math.IsInf(f, -1):
462 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
463 case math.IsInf(f, 1):
464 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
465 case math.IsNaN(f):
466 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
467 default:
Damien Neil982684b2018-09-28 14:12:41 -0700468 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700469 }
470 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700471 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700472 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
473 }
474 }
475 g.P()
476
Joe Tsai61968ce2019-04-01 12:59:24 -0700477 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700478 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700479 if isFirstOneofField(field) {
480 genOneofGetter(gen, g, f, message, field.OneofType)
Damien Neil1fa78d82018-09-13 13:12:36 -0700481 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700482 goType, pointer := fieldGoType(g, field)
483 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800484 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700485 g.P(deprecationComment(true))
486 }
Damien Neil162c1272018-10-04 12:42:37 -0700487 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700488 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700489 if field.OneofType != nil {
Joe Tsai61968ce2019-04-01 12:59:24 -0700490 g.P("if x, ok := x.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700491 g.P("return x.", field.GoName)
492 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700493 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700494 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700495 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700496 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700497 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700498 }
499 star := ""
500 if pointer {
501 star = "*"
502 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700503 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700504 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700505 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700506 g.P("return ", defaultValue)
507 g.P("}")
508 g.P()
509 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700510
Joe Tsai872b5002019-04-08 14:03:15 -0700511 // XXX_OneofWrappers method.
Damien Neil1fa78d82018-09-13 13:12:36 -0700512 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800513 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700514 }
Joe Tsai872b5002019-04-08 14:03:15 -0700515
516 // Oneof wrapper types.
517 for _, oneof := range message.Oneofs {
518 genOneofTypes(gen, g, f, message, oneof)
519 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700520}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700521
Damien Neil77f82fe2018-09-13 10:59:17 -0700522// fieldGoType returns the Go type used for a field.
523//
524// If it returns pointer=true, the struct field is a pointer to the type.
525func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700526 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700527 switch field.Desc.Kind() {
528 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700529 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700530 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700531 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700532 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700533 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700534 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700535 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700536 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700537 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700538 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700539 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700540 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700541 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700542 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700543 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700544 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700545 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700546 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700547 goType = "[]byte"
548 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700549 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700550 if field.Desc.IsMap() {
551 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
552 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
553 return fmt.Sprintf("map[%v]%v", keyType, valType), false
554 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700555 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
556 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700557 }
558 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700559 goType = "[]" + goType
560 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700561 }
Damien Neil44000a12018-10-24 12:31:16 -0700562 // Extension fields always have pointer type, even when defined in a proto3 file.
563 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700564 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700565 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700566 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700567}
568
569func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700570 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700571 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai61968ce2019-04-01 12:59:24 -0700572 enumName = enumLegacyName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700573 }
Joe Tsai05828db2018-11-01 13:52:16 -0700574 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700575}
576
Damien Neil77f82fe2018-09-13 10:59:17 -0700577func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
578 if field.Desc.Cardinality() == protoreflect.Repeated {
579 return "nil"
580 }
Joe Tsai9667c482018-12-05 15:42:52 -0800581 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700582 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700583 if field.Desc.Kind() == protoreflect.BytesKind {
584 return "append([]byte(nil), " + defVarName + "...)"
585 }
586 return defVarName
587 }
588 switch field.Desc.Kind() {
589 case protoreflect.BoolKind:
590 return "false"
591 case protoreflect.StringKind:
592 return `""`
593 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
594 return "nil"
595 case protoreflect.EnumKind:
596 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
597 default:
598 return "0"
599 }
600}
601
Damien Neil658051b2018-09-10 12:26:21 -0700602func fieldJSONTag(field *protogen.Field) string {
603 return string(field.Desc.Name()) + ",omitempty"
604}
605
Joe Tsaiafb455e2019-03-14 16:08:22 -0700606func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
607 if len(f.allExtensions) == 0 {
608 return
Damien Neil154da982018-09-19 13:21:58 -0700609 }
610
Joe Tsai4fddeba2019-03-20 18:29:32 -0700611 g.P("var ", extDecsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700612 for _, extension := range f.allExtensions {
613 // Special case for proto2 message sets: If this extension is extending
614 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
615 // then drop that last component.
616 //
617 // TODO: This should be implemented in the text formatter rather than the generator.
618 // In addition, the situation for when to apply this special case is implemented
619 // differently in other languages:
620 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
621 name := extension.Desc.FullName()
622 if n, ok := isExtensionMessageSetElement(extension); ok {
623 name = n
624 }
625
626 g.P("{")
627 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
628 goType, pointer := fieldGoType(g, extension)
629 if pointer {
630 goType = "*" + goType
631 }
632 g.P("ExtensionType: (", goType, ")(nil),")
633 g.P("Field: ", extension.Desc.Number(), ",")
634 g.P("Name: ", strconv.Quote(string(name)), ",")
635 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
636 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
637 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700638 }
Damien Neil993c04d2018-09-14 15:41:11 -0700639 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700640
641 g.P("var (")
642 for i, extension := range f.allExtensions {
643 ed := extension.Desc
644 targetName := string(ed.ExtendedType().FullName())
645 typeName := ed.Kind().String()
646 switch ed.Kind() {
647 case protoreflect.EnumKind:
648 typeName = string(ed.EnumType().FullName())
649 case protoreflect.MessageKind, protoreflect.GroupKind:
650 typeName = string(ed.MessageType().FullName())
651 }
652 fieldName := string(ed.Name())
653 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
654 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
655 g.P()
656 }
657 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700658}
659
Damien Neil62386962018-10-30 10:35:48 -0700660// isExtensionMessageSetELement returns the adjusted name of an extension
661// which extends proto2.bridge.MessageSet.
662func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800663 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700664 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
665 return "", false
666 }
667 if extension.ParentMessage == nil {
668 // This case shouldn't be given special handling at all--we're
669 // only supposed to drop the ".message_set_extension" for
670 // extensions defined within a message (i.e., the extension
671 // takes the message's name).
672 //
673 // This matches the behavior of the v1 generator, however.
674 //
675 // TODO: See if we can drop this case.
676 name = extension.Desc.FullName()
677 name = name[:len(name)-len("message_set_extension")]
678 return name, true
679 }
680 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700681}
682
Damien Neil993c04d2018-09-14 15:41:11 -0700683// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700684func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700685 name := "E_"
686 if extension.ParentMessage != nil {
687 name += extension.ParentMessage.GoIdent.GoName + "_"
688 }
689 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800690 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700691}
692
Damien Neil55fe1c02018-09-17 15:11:24 -0700693// deprecationComment returns a standard deprecation comment if deprecated is true.
694func deprecationComment(deprecated bool) string {
695 if !deprecated {
696 return ""
697 }
698 return "// Deprecated: Do not use."
699}
700
Joe Tsai61968ce2019-04-01 12:59:24 -0700701// TODO: Remove this. This was added to aid jsonpb, but jsonpb does this work
702// through the use of protobuf reflection now.
Damien Neilea7baf42018-09-28 14:23:44 -0700703func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700704 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700705 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700706 g.P()
707 }
708}
709
710// Names of messages and enums for which we will generate XXX_WellKnownType methods.
711var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700712 "google.protobuf.Any": true,
713 "google.protobuf.Duration": true,
714 "google.protobuf.Empty": true,
715 "google.protobuf.Struct": true,
716 "google.protobuf.Timestamp": true,
717
718 "google.protobuf.BoolValue": true,
719 "google.protobuf.BytesValue": true,
720 "google.protobuf.DoubleValue": true,
721 "google.protobuf.FloatValue": true,
722 "google.protobuf.Int32Value": true,
723 "google.protobuf.Int64Value": true,
724 "google.protobuf.ListValue": true,
725 "google.protobuf.NullValue": true,
726 "google.protobuf.StringValue": true,
727 "google.protobuf.UInt32Value": true,
728 "google.protobuf.UInt64Value": true,
729 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700730}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800731
732// genOneofField generates the struct field for a oneof.
733func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
734 if g.PrintLeadingComments(oneof.Location) {
735 g.P("//")
736 }
737 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
738 for _, field := range oneof.Fields {
739 g.PrintLeadingComments(field.Location)
740 g.P("//\t*", fieldOneofType(field))
741 }
742 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
743 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
744}
745
Joe Tsai872b5002019-04-08 14:03:15 -0700746// genOneofGetter generate a Get method for a oneof.
747func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
748 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
749 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
750 g.P("if m != nil {")
751 g.P("return m.", oneofFieldName(oneof))
752 g.P("}")
753 g.P("return nil")
754 g.P("}")
755 g.P()
756}
757
758// genOneofWrappers generates the XXX_OneofWrappers method for a message.
759func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
760 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
761 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
762 g.P("return []interface{}{")
763 for _, oneof := range message.Oneofs {
764 for _, field := range oneof.Fields {
765 g.P("(*", fieldOneofType(field), ")(nil),")
766 }
767 }
768 g.P("}")
769 g.P("}")
770 g.P()
771}
772
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800773// genOneofTypes generates the interface type used for a oneof field,
774// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800775func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
776 ifName := oneofInterfaceName(oneof)
777 g.P("type ", ifName, " interface {")
778 g.P(ifName, "()")
779 g.P("}")
780 g.P()
781 for _, field := range oneof.Fields {
782 name := fieldOneofType(field)
783 g.Annotate(name.GoName, field.Location)
784 g.Annotate(name.GoName+"."+field.GoName, field.Location)
785 g.P("type ", name, " struct {")
786 goType, _ := fieldGoType(g, field)
787 tags := []string{
788 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
789 }
790 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
791 g.P("}")
792 g.P()
793 }
794 for _, field := range oneof.Fields {
795 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
796 g.P()
797 }
Joe Tsai872b5002019-04-08 14:03:15 -0700798}
799
800// isFirstOneofField reports whether this is the first field in a oneof.
801func isFirstOneofField(field *protogen.Field) bool {
802 return field.OneofType != nil && field.OneofType.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800803}
804
805// oneofFieldName returns the name of the struct field holding the oneof value.
806//
807// This function is trivial, but pulling out the name like this makes it easier
808// to experiment with alternative oneof implementations.
809func oneofFieldName(oneof *protogen.Oneof) string {
810 return oneof.GoName
811}
812
813// oneofInterfaceName returns the name of the interface type implemented by
814// the oneof field value types.
815func oneofInterfaceName(oneof *protogen.Oneof) string {
816 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
817}
818
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800819// fieldOneofType returns the wrapper type used to represent a field in a oneof.
820func fieldOneofType(field *protogen.Field) protogen.GoIdent {
821 ident := protogen.GoIdent{
822 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
823 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
824 }
825 // Check for collisions with nested messages or enums.
826 //
827 // This conflict resolution is incomplete: Among other things, it
828 // does not consider collisions with other oneof field types.
829 //
830 // TODO: Consider dropping this entirely. Detecting conflicts and
831 // producing an error is almost certainly better than permuting
832 // field and type names in mostly unpredictable ways.
833Loop:
834 for {
835 for _, message := range field.ParentMessage.Messages {
836 if message.GoIdent == ident {
837 ident.GoName += "_"
838 continue Loop
839 }
840 }
841 for _, enum := range field.ParentMessage.Enums {
842 if enum.GoIdent == ident {
843 ident.GoName += "_"
844 continue Loop
845 }
846 }
847 return ident
848 }
849}