blob: a17af0680b556e3c3ab61116785ed4bb2b3b84a2 [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
Damien Neil5c5b5312019-05-14 12:44:37 -070019 "google.golang.org/protobuf/compiler/protogen"
Damien Neile89e6242019-05-13 23:55:40 -070020 "google.golang.org/protobuf/internal/encoding/tag"
21 "google.golang.org/protobuf/internal/fieldnum"
Damien Neile89e6242019-05-13 23:55:40 -070022 "google.golang.org/protobuf/reflect/protoreflect"
Joe Tsai58b42d82019-05-22 16:27:51 -040023 "google.golang.org/protobuf/runtime/protoimpl"
Joe Tsaie1f8d502018-11-26 18:55:29 -080024
Joe Tsaia95b29f2019-05-16 12:47:20 -070025 "google.golang.org/protobuf/types/descriptorpb"
Damien Neil220c2022018-08-15 11:24:18 -070026)
27
Joe Tsaic1c17aa2018-11-16 11:14:14 -080028const (
Joe Tsaiab61d412019-04-16 15:23:29 -070029 // generateEnumMapVars specifies whether to generate enum maps,
30 // which provide a bi-directional mapping between enum numbers and names.
31 generateEnumMapVars = true
32
33 // generateRawDescMethods specifies whether to generate EnumDescriptor and
34 // Descriptor methods for enums and messages. These methods return the
35 // GZIP'd contents of the raw file descriptor and the path from the root
36 // to the given enum or message descriptor.
37 generateRawDescMethods = true
38)
39
40const (
Joe Tsai5d72cc22019-03-28 01:13:26 -070041 syncPackage = protogen.GoImportPath("sync")
Joe Tsai4fddeba2019-03-20 18:29:32 -070042 mathPackage = protogen.GoImportPath("math")
Damien Neile89e6242019-05-13 23:55:40 -070043 protoifacePackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoiface")
44 protoimplPackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoimpl")
45 protoreflectPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoreflect")
46 protoregistryPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoregistry")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080047)
Damien Neil46abb572018-09-07 12:45:37 -070048
Damien Neild39efc82018-09-24 12:38:10 -070049type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070050 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080051
Joe Tsai9667c482018-12-05 15:42:52 -080052 allEnums []*protogen.Enum
53 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
54 allMessages []*protogen.Message
55 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
56 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070057}
58
Damien Neil9c420a62018-09-27 15:26:33 -070059// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080060func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
61 filename := file.GeneratedFilenamePrefix + ".pb.go"
62 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070063 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070064 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070065 }
66
Damien Neil8012b442019-01-18 09:32:24 -080067 // Collect all enums, messages, and extensions in "flattened ordering".
68 // See fileinit.FileBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080069 f.allEnums = append(f.allEnums, f.Enums...)
70 f.allMessages = append(f.allMessages, f.Messages...)
71 f.allExtensions = append(f.allExtensions, f.Extensions...)
72 walkMessages(f.Messages, func(m *protogen.Message) {
73 f.allEnums = append(f.allEnums, m.Enums...)
74 f.allMessages = append(f.allMessages, m.Messages...)
75 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070076 })
Damien Neilce36f8d2018-09-13 15:19:08 -070077
Joe Tsai9667c482018-12-05 15:42:52 -080078 // Derive a reverse mapping of enum and message pointers to their index
79 // in allEnums and allMessages.
80 if len(f.allEnums) > 0 {
81 f.allEnumsByPtr = make(map[*protogen.Enum]int)
82 for i, e := range f.allEnums {
83 f.allEnumsByPtr[e] = i
84 }
85 }
86 if len(f.allMessages) > 0 {
87 f.allMessagesByPtr = make(map[*protogen.Message]int)
88 for i, m := range f.allMessages {
89 f.allMessagesByPtr[m] = i
90 }
91 }
Joe Tsaib6405bd2018-11-15 14:44:37 -080092
Damien Neil220c2022018-08-15 11:24:18 -070093 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070094 if f.Proto.GetOptions().GetDeprecated() {
95 g.P("// ", f.Desc.Path(), " is a deprecated file.")
96 } else {
97 g.P("// source: ", f.Desc.Path())
98 }
Damien Neil220c2022018-08-15 11:24:18 -070099 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -0700100 g.PrintLeadingComments(protogen.Location{
101 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -0700102 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700103 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700104 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700105 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700106 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700107
Joe Tsai5d72cc22019-03-28 01:13:26 -0700108 // Emit a static check that enforces a minimum version of the proto package.
Joe Tsai58b42d82019-05-22 16:27:51 -0400109 g.P("const (")
110 g.P("// Verify that runtime/protoimpl is sufficiently up-to-date.")
111 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("MaxVersion"), " - ", protoimpl.Version, ")")
112 g.P("// Verify that this generated code is sufficiently up-to-date.")
113 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimpl.Version, " - ", protoimplPackage.Ident("MinVersion"), ")")
114 g.P(")")
Joe Tsai5d72cc22019-03-28 01:13:26 -0700115 g.P()
116
Damien Neil73ac8852018-09-17 15:11:24 -0700117 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
118 genImport(gen, g, f, imps.Get(i))
119 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700120 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700121 genEnum(gen, g, f, enum)
122 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700123 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700124 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700125 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700126 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700127
Joe Tsaib6405bd2018-11-15 14:44:37 -0800128 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800129
130 return g
Damien Neil7779e052018-09-07 14:14:06 -0700131}
132
Damien Neil73ac8852018-09-17 15:11:24 -0700133// walkMessages calls f on each message and all of its descendants.
134func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
135 for _, m := range messages {
136 f(m)
137 walkMessages(m.Messages, f)
138 }
139}
140
Damien Neild39efc82018-09-24 12:38:10 -0700141func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700142 impFile, ok := gen.FileByName(imp.Path())
143 if !ok {
144 return
145 }
146 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700147 // Don't generate imports or aliases for types in the same Go package.
148 return
149 }
Damien Neil40a08052018-10-29 09:07:41 -0700150 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700151 // referenced, because other code and tools depend on having the
152 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700153 if !imp.IsWeak {
154 g.Import(impFile.GoImportPath)
155 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700156 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700157 return
158 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800159
160 // Generate public imports by generating the imported file, parsing it,
161 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800162 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800163 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800164 b, err := impGen.Content()
165 if err != nil {
166 gen.Error(err)
167 return
168 }
169 fset := token.NewFileSet()
170 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
171 if err != nil {
172 gen.Error(err)
173 return
174 }
Damien Neila7cbd062019-01-06 16:29:14 -0800175 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800176 // Don't import unexported symbols.
177 r, _ := utf8.DecodeRuneInString(name)
178 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700179 return
180 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800181 // Don't import the FileDescriptor.
182 if name == impFile.GoDescriptorIdent.GoName {
183 return
184 }
Damien Neila7cbd062019-01-06 16:29:14 -0800185 // Don't import decls referencing a symbol defined in another package.
186 // i.e., don't import decls which are themselves public imports:
187 //
188 // type T = somepackage.T
189 if _, ok := expr.(*ast.SelectorExpr); ok {
190 return
191 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800192 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
193 }
194 g.P("// Symbols defined in public import of ", imp.Path())
195 g.P()
196 for _, decl := range astFile.Decls {
197 switch decl := decl.(type) {
198 case *ast.GenDecl:
199 for _, spec := range decl.Specs {
200 switch spec := spec.(type) {
201 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800202 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800203 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800204 for i, name := range spec.Names {
205 var expr ast.Expr
206 if i < len(spec.Values) {
207 expr = spec.Values[i]
208 }
209 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800210 }
211 case *ast.ImportSpec:
212 default:
213 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800214 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700215 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700216 }
Damien Neil6b541312018-10-29 09:14:14 -0700217 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700218 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700219}
220
Damien Neild39efc82018-09-24 12:38:10 -0700221func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Joe Tsai61968ce2019-04-01 12:59:24 -0700222 // Enum type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700223 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700224 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700225 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800226 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Joe Tsai61968ce2019-04-01 12:59:24 -0700227
228 // Enum value constants.
Damien Neil46abb572018-09-07 12:45:37 -0700229 g.P("const (")
230 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700231 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700232 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700233 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800234 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700235 }
236 g.P(")")
237 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800238
Joe Tsai61968ce2019-04-01 12:59:24 -0700239 // Enum value mapping (number -> name).
Joe Tsaiab61d412019-04-16 15:23:29 -0700240 if generateEnumMapVars {
241 nameMap := enum.GoIdent.GoName + "_name"
242 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
243 g.P("var ", nameMap, " = map[int32]string{")
244 generated := make(map[protoreflect.EnumNumber]bool)
245 for _, value := range enum.Values {
246 duplicate := ""
247 if _, present := generated[value.Desc.Number()]; present {
248 duplicate = "// Duplicate value: "
249 }
250 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
251 generated[value.Desc.Number()] = true
Damien Neil46abb572018-09-07 12:45:37 -0700252 }
Joe Tsaiab61d412019-04-16 15:23:29 -0700253 g.P("}")
254 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700255 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700256
Joe Tsai61968ce2019-04-01 12:59:24 -0700257 // Enum value mapping (name -> number).
Joe Tsaiab61d412019-04-16 15:23:29 -0700258 if generateEnumMapVars {
259 valueMap := enum.GoIdent.GoName + "_value"
260 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
261 g.P("var ", valueMap, " = map[string]int32{")
262 for _, value := range enum.Values {
263 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
264 }
265 g.P("}")
266 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700267 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700268
Joe Tsai61968ce2019-04-01 12:59:24 -0700269 // Enum method.
Joe Tsaidbab6c02019-05-14 15:06:03 -0700270 //
271 // NOTE: A pointer value is needed to represent presence in proto2.
272 // Since a proto2 message can reference a proto3 enum, it is useful to
273 // always generate this method (even on proto3 enums) to support that case.
274 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
275 g.P("p := new(", enum.GoIdent, ")")
276 g.P("*p = x")
277 g.P("return p")
278 g.P("}")
279 g.P()
280
Joe Tsai61968ce2019-04-01 12:59:24 -0700281 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700282 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700283 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700284 g.P("}")
285 g.P()
286
Joe Tsai61968ce2019-04-01 12:59:24 -0700287 genReflectEnum(gen, g, f, enum)
288
289 // UnmarshalJSON method.
Joe Tsai73903462018-12-14 12:22:41 -0800290 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700291 g.P("// Deprecated: Do not use.")
292 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700293 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700294 g.P("if err != nil {")
295 g.P("return err")
296 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700297 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700298 g.P("return nil")
299 g.P("}")
300 g.P()
301 }
302
Joe Tsai61968ce2019-04-01 12:59:24 -0700303 // EnumDescriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700304 if generateRawDescMethods {
305 var indexes []string
306 for i := 1; i < len(enum.Location.Path); i += 2 {
307 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
308 }
309 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
310 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
311 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
312 g.P("}")
313 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700314 }
Damien Neil46abb572018-09-07 12:45:37 -0700315
Damien Neilea7baf42018-09-28 14:23:44 -0700316 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700317}
318
Joe Tsai61968ce2019-04-01 12:59:24 -0700319// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700320//
321// Confusingly, this is <proto_package>.<go_ident>. This probably should have
322// been the full name of the proto enum type instead, but changing it at this
323// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700324func enumLegacyName(enum *protogen.Enum) string {
Joe Tsai67c1d9b2019-05-12 02:27:46 -0700325 fdesc := enum.Desc.ParentFile()
Damien Neildaa4fad2018-10-08 14:08:27 -0700326 if fdesc.Package() == "" {
327 return enum.GoIdent.GoName
328 }
Damien Neil658051b2018-09-10 12:26:21 -0700329 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
330}
331
Damien Neild39efc82018-09-24 12:38:10 -0700332func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700333 if message.Desc.IsMapEntry() {
334 return
335 }
336
Joe Tsai61968ce2019-04-01 12:59:24 -0700337 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700338 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800339 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700340 if hasComment {
341 g.P("//")
342 }
343 g.P(deprecationComment(true))
344 }
Damien Neil162c1272018-10-04 12:42:37 -0700345 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700346 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700347 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700348 if field.Oneof != nil {
Damien Neil1fa78d82018-09-13 13:12:36 -0700349 // It would be a bit simpler to iterate over the oneofs below,
350 // but generating the field here keeps the contents of the Go
351 // struct in the same order as the contents of the source
352 // .proto file.
Joe Tsaid24bc722019-04-15 23:39:09 -0700353 if field == field.Oneof.Fields[0] {
354 genOneofField(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700355 }
Damien Neil658051b2018-09-10 12:26:21 -0700356 continue
357 }
Damien Neilba1159f2018-10-17 12:53:18 -0700358 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700359 goType, pointer := fieldGoType(g, field)
360 if pointer {
361 goType = "*" + goType
362 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700363 tags := []string{
364 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
365 fmt.Sprintf("json:%q", fieldJSONTag(field)),
366 }
367 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700368 key := field.Message.Fields[0]
369 val := field.Message.Fields[1]
Damien Neil0bd5a382018-09-13 15:07:10 -0700370 tags = append(tags,
371 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
372 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
373 )
374 }
Damien Neil162c1272018-10-04 12:42:37 -0700375 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700376 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800377 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700378 }
379 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700380
381 if message.Desc.ExtensionRanges().Len() > 0 {
382 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800383 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700384 tags = append(tags, `protobuf_messageset:"1"`)
385 }
386 tags = append(tags, `json:"-"`)
Joe Tsai5e71dc92019-04-16 13:22:20 -0700387 g.P("XXX_InternalExtensions ", protoimplPackage.Ident("ExtensionFields"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700388 }
Joe Tsai5e71dc92019-04-16 13:22:20 -0700389 g.P("XXX_unrecognized ", protoimplPackage.Ident("UnknownFields"), " `json:\"-\"`")
390 g.P("XXX_sizecache ", protoimplPackage.Ident("SizeCache"), " `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700391 g.P("}")
392 g.P()
393
Joe Tsai61968ce2019-04-01 12:59:24 -0700394 // Reset method.
395 g.P("func (x *", message.GoIdent, ") Reset() {")
396 g.P("*x = ", message.GoIdent, "{}")
397 g.P("}")
398 g.P()
399 // String method.
400 g.P("func (x *", message.GoIdent, ") String() string {")
401 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
402 g.P("}")
403 g.P()
404 // ProtoMessage method.
405 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
406 g.P()
407
Joe Tsaib6405bd2018-11-15 14:44:37 -0800408 genReflectMessage(gen, g, f, message)
409
Joe Tsai61968ce2019-04-01 12:59:24 -0700410 // Descriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700411 if generateRawDescMethods {
412 var indexes []string
413 for i := 1; i < len(message.Location.Path); i += 2 {
414 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
415 }
416 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
417 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
418 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
419 g.P("}")
420 g.P()
Damien Neila1c6abc2018-09-12 13:36:34 -0700421 }
Damien Neil993c04d2018-09-14 15:41:11 -0700422
Joe Tsai61968ce2019-04-01 12:59:24 -0700423 // ExtensionRangeArray method.
Damien Neil993c04d2018-09-14 15:41:11 -0700424 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700425 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700426 extRangeVar := "extRange_" + message.GoIdent.GoName
427 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
428 for i := 0; i < extranges.Len(); i++ {
429 r := extranges.Get(i)
430 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
431 }
432 g.P("}")
433 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700434 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700435 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
436 g.P("return ", extRangeVar)
437 g.P("}")
438 g.P()
439 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700440
Damien Neilea7baf42018-09-28 14:23:44 -0700441 genWellKnownType(g, "*", message.GoIdent, message.Desc)
442
Damien Neilebc699d2018-09-13 08:50:13 -0700443 // Constants and vars holding the default values of fields.
444 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800445 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700446 continue
447 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700448 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700449 def := field.Desc.Default()
450 switch field.Desc.Kind() {
451 case protoreflect.StringKind:
452 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
453 case protoreflect.BytesKind:
454 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
455 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700456 evalueDesc := field.Desc.DefaultEnumValue()
Joe Tsaid24bc722019-04-15 23:39:09 -0700457 enum := field.Enum
Damien Neila485fbd2018-10-26 13:28:37 -0700458 evalue := enum.Values[evalueDesc.Index()]
Joe Tsaid24bc722019-04-15 23:39:09 -0700459 g.P("const ", defVarName, " ", field.Enum.GoIdent, " = ", evalue.GoIdent)
Damien Neilebc699d2018-09-13 08:50:13 -0700460 case protoreflect.FloatKind, protoreflect.DoubleKind:
461 // Floating point numbers need extra handling for -Inf/Inf/NaN.
462 f := field.Desc.Default().Float()
463 goType := "float64"
464 if field.Desc.Kind() == protoreflect.FloatKind {
465 goType = "float32"
466 }
467 // funcCall returns a call to a function in the math package,
468 // possibly converting the result to float32.
469 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800470 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700471 if goType != "float64" {
472 s = goType + "(" + s + ")"
473 }
474 return s
475 }
476 switch {
477 case math.IsInf(f, -1):
478 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
479 case math.IsInf(f, 1):
480 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
481 case math.IsNaN(f):
482 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
483 default:
Damien Neil982684b2018-09-28 14:12:41 -0700484 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700485 }
486 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700487 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700488 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
489 }
490 }
491 g.P()
492
Joe Tsai61968ce2019-04-01 12:59:24 -0700493 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700494 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700495 if isFirstOneofField(field) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700496 genOneofGetter(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700497 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700498 goType, pointer := fieldGoType(g, field)
499 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800500 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700501 g.P(deprecationComment(true))
502 }
Damien Neil162c1272018-10-04 12:42:37 -0700503 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700504 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Joe Tsaid24bc722019-04-15 23:39:09 -0700505 if field.Oneof != nil {
506 g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700507 g.P("return x.", field.GoName)
508 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700509 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700510 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700511 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700512 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700513 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700514 }
515 star := ""
516 if pointer {
517 star = "*"
518 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700519 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700520 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700521 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700522 g.P("return ", defaultValue)
523 g.P("}")
524 g.P()
525 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700526
Joe Tsai872b5002019-04-08 14:03:15 -0700527 // XXX_OneofWrappers method.
Damien Neil1fa78d82018-09-13 13:12:36 -0700528 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800529 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700530 }
Joe Tsai872b5002019-04-08 14:03:15 -0700531
532 // Oneof wrapper types.
533 for _, oneof := range message.Oneofs {
534 genOneofTypes(gen, g, f, message, oneof)
535 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700536}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700537
Damien Neil77f82fe2018-09-13 10:59:17 -0700538// fieldGoType returns the Go type used for a field.
539//
540// If it returns pointer=true, the struct field is a pointer to the type.
541func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700542 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700543 switch field.Desc.Kind() {
544 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700545 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700546 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700547 goType = g.QualifiedGoIdent(field.Enum.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700548 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700549 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700550 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700551 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700552 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700553 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700554 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700555 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700556 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700557 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700558 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700559 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700560 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700561 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700562 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700563 goType = "[]byte"
564 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700565 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700566 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700567 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700568 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700569 switch {
570 case field.Desc.IsList():
Damien Neil77f82fe2018-09-13 10:59:17 -0700571 goType = "[]" + goType
572 pointer = false
Joe Tsaiac31a352019-05-13 14:32:56 -0700573 case field.Desc.IsMap():
574 keyType, _ := fieldGoType(g, field.Message.Fields[0])
575 valType, _ := fieldGoType(g, field.Message.Fields[1])
576 return fmt.Sprintf("map[%v]%v", keyType, valType), false
Damien Neil658051b2018-09-10 12:26:21 -0700577 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700578
Damien Neil44000a12018-10-24 12:31:16 -0700579 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaiac31a352019-05-13 14:32:56 -0700580 if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700581 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700582 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700583 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700584}
585
586func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700587 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700588 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700589 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700590 }
Joe Tsai05828db2018-11-01 13:52:16 -0700591 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700592}
593
Damien Neil77f82fe2018-09-13 10:59:17 -0700594func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
Joe Tsaiac31a352019-05-13 14:32:56 -0700595 if field.Desc.IsList() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700596 return "nil"
597 }
Joe Tsai9667c482018-12-05 15:42:52 -0800598 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700599 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700600 if field.Desc.Kind() == protoreflect.BytesKind {
601 return "append([]byte(nil), " + defVarName + "...)"
602 }
603 return defVarName
604 }
605 switch field.Desc.Kind() {
606 case protoreflect.BoolKind:
607 return "false"
608 case protoreflect.StringKind:
609 return `""`
610 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
611 return "nil"
612 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700613 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 default:
615 return "0"
616 }
617}
618
Damien Neil658051b2018-09-10 12:26:21 -0700619func fieldJSONTag(field *protogen.Field) string {
620 return string(field.Desc.Name()) + ",omitempty"
621}
622
Joe Tsaiafb455e2019-03-14 16:08:22 -0700623func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
624 if len(f.allExtensions) == 0 {
625 return
Damien Neil154da982018-09-19 13:21:58 -0700626 }
627
Joe Tsai4fddeba2019-03-20 18:29:32 -0700628 g.P("var ", extDecsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700629 for _, extension := range f.allExtensions {
630 // Special case for proto2 message sets: If this extension is extending
631 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
632 // then drop that last component.
633 //
634 // TODO: This should be implemented in the text formatter rather than the generator.
635 // In addition, the situation for when to apply this special case is implemented
636 // differently in other languages:
637 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
638 name := extension.Desc.FullName()
639 if n, ok := isExtensionMessageSetElement(extension); ok {
640 name = n
641 }
642
643 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700644 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700645 goType, pointer := fieldGoType(g, extension)
646 if pointer {
647 goType = "*" + goType
648 }
649 g.P("ExtensionType: (", goType, ")(nil),")
650 g.P("Field: ", extension.Desc.Number(), ",")
651 g.P("Name: ", strconv.Quote(string(name)), ",")
652 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
653 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
654 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700655 }
Damien Neil993c04d2018-09-14 15:41:11 -0700656 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700657
658 g.P("var (")
659 for i, extension := range f.allExtensions {
660 ed := extension.Desc
Joe Tsaiac31a352019-05-13 14:32:56 -0700661 targetName := string(ed.ContainingMessage().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700662 typeName := ed.Kind().String()
663 switch ed.Kind() {
664 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700665 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700666 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700667 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700668 }
669 fieldName := string(ed.Name())
670 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
671 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
672 g.P()
673 }
674 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700675}
676
Damien Neil62386962018-10-30 10:35:48 -0700677// isExtensionMessageSetELement returns the adjusted name of an extension
678// which extends proto2.bridge.MessageSet.
679func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700680 opts := extension.Extendee.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700681 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
682 return "", false
683 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700684 if extension.Parent == nil {
Damien Neil62386962018-10-30 10:35:48 -0700685 // This case shouldn't be given special handling at all--we're
686 // only supposed to drop the ".message_set_extension" for
687 // extensions defined within a message (i.e., the extension
688 // takes the message's name).
689 //
690 // This matches the behavior of the v1 generator, however.
691 //
692 // TODO: See if we can drop this case.
693 name = extension.Desc.FullName()
694 name = name[:len(name)-len("message_set_extension")]
695 return name, true
696 }
697 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700698}
699
Damien Neil993c04d2018-09-14 15:41:11 -0700700// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700701func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700702 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700703 if extension.Parent != nil {
704 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700705 }
706 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800707 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700708}
709
Damien Neil55fe1c02018-09-17 15:11:24 -0700710// deprecationComment returns a standard deprecation comment if deprecated is true.
711func deprecationComment(deprecated bool) string {
712 if !deprecated {
713 return ""
714 }
715 return "// Deprecated: Do not use."
716}
717
Damien Neil5c5b5312019-05-14 12:44:37 -0700718// TODO: Remove this. This was added to aid protojson, but protojson does this work
Joe Tsai61968ce2019-04-01 12:59:24 -0700719// through the use of protobuf reflection now.
Damien Neilea7baf42018-09-28 14:23:44 -0700720func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700721 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700722 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700723 g.P()
724 }
725}
726
727// Names of messages and enums for which we will generate XXX_WellKnownType methods.
728var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700729 "google.protobuf.Any": true,
730 "google.protobuf.Duration": true,
731 "google.protobuf.Empty": true,
732 "google.protobuf.Struct": true,
733 "google.protobuf.Timestamp": true,
734
735 "google.protobuf.BoolValue": true,
736 "google.protobuf.BytesValue": true,
737 "google.protobuf.DoubleValue": true,
738 "google.protobuf.FloatValue": true,
739 "google.protobuf.Int32Value": true,
740 "google.protobuf.Int64Value": true,
741 "google.protobuf.ListValue": true,
742 "google.protobuf.NullValue": true,
743 "google.protobuf.StringValue": true,
744 "google.protobuf.UInt32Value": true,
745 "google.protobuf.UInt64Value": true,
746 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700747}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800748
749// genOneofField generates the struct field for a oneof.
750func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
751 if g.PrintLeadingComments(oneof.Location) {
752 g.P("//")
753 }
754 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
755 for _, field := range oneof.Fields {
756 g.PrintLeadingComments(field.Location)
757 g.P("//\t*", fieldOneofType(field))
758 }
759 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
760 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
761}
762
Joe Tsai872b5002019-04-08 14:03:15 -0700763// genOneofGetter generate a Get method for a oneof.
764func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
765 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
766 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
767 g.P("if m != nil {")
768 g.P("return m.", oneofFieldName(oneof))
769 g.P("}")
770 g.P("return nil")
771 g.P("}")
772 g.P()
773}
774
775// genOneofWrappers generates the XXX_OneofWrappers method for a message.
776func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
777 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
778 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
779 g.P("return []interface{}{")
780 for _, oneof := range message.Oneofs {
781 for _, field := range oneof.Fields {
782 g.P("(*", fieldOneofType(field), ")(nil),")
783 }
784 }
785 g.P("}")
786 g.P("}")
787 g.P()
788}
789
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800790// genOneofTypes generates the interface type used for a oneof field,
791// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800792func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
793 ifName := oneofInterfaceName(oneof)
794 g.P("type ", ifName, " interface {")
795 g.P(ifName, "()")
796 g.P("}")
797 g.P()
798 for _, field := range oneof.Fields {
799 name := fieldOneofType(field)
800 g.Annotate(name.GoName, field.Location)
801 g.Annotate(name.GoName+"."+field.GoName, field.Location)
802 g.P("type ", name, " struct {")
803 goType, _ := fieldGoType(g, field)
804 tags := []string{
805 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
806 }
807 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
808 g.P("}")
809 g.P()
810 }
811 for _, field := range oneof.Fields {
812 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
813 g.P()
814 }
Joe Tsai872b5002019-04-08 14:03:15 -0700815}
816
817// isFirstOneofField reports whether this is the first field in a oneof.
818func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700819 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800820}
821
822// oneofFieldName returns the name of the struct field holding the oneof value.
823//
824// This function is trivial, but pulling out the name like this makes it easier
825// to experiment with alternative oneof implementations.
826func oneofFieldName(oneof *protogen.Oneof) string {
827 return oneof.GoName
828}
829
830// oneofInterfaceName returns the name of the interface type implemented by
831// the oneof field value types.
832func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700833 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800834}
835
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800836// fieldOneofType returns the wrapper type used to represent a field in a oneof.
837func fieldOneofType(field *protogen.Field) protogen.GoIdent {
838 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700839 GoImportPath: field.Parent.GoIdent.GoImportPath,
840 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800841 }
842 // Check for collisions with nested messages or enums.
843 //
844 // This conflict resolution is incomplete: Among other things, it
845 // does not consider collisions with other oneof field types.
846 //
847 // TODO: Consider dropping this entirely. Detecting conflicts and
848 // producing an error is almost certainly better than permuting
849 // field and type names in mostly unpredictable ways.
850Loop:
851 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700852 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800853 if message.GoIdent == ident {
854 ident.GoName += "_"
855 continue Loop
856 }
857 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700858 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800859 if enum.GoIdent == ident {
860 ident.GoName += "_"
861 continue Loop
862 }
863 }
864 return ident
865 }
866}