blob: b3556a4c4825b6547d40235f7b555bc4585e6d74 [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 Tsaid8881392019-06-06 13:01:53 -070047 prototypePackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/prototype")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080048)
Damien Neil46abb572018-09-07 12:45:37 -070049
Damien Neild39efc82018-09-24 12:38:10 -070050type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070051 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080052
Joe Tsai9667c482018-12-05 15:42:52 -080053 allEnums []*protogen.Enum
54 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
55 allMessages []*protogen.Message
56 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
57 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070058}
59
Damien Neil9c420a62018-09-27 15:26:33 -070060// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080061func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
62 filename := file.GeneratedFilenamePrefix + ".pb.go"
63 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070064 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070065 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070066 }
67
Damien Neil8012b442019-01-18 09:32:24 -080068 // Collect all enums, messages, and extensions in "flattened ordering".
Joe Tsaid8881392019-06-06 13:01:53 -070069 // See filetype.TypeBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080070 f.allEnums = append(f.allEnums, f.Enums...)
71 f.allMessages = append(f.allMessages, f.Messages...)
72 f.allExtensions = append(f.allExtensions, f.Extensions...)
73 walkMessages(f.Messages, func(m *protogen.Message) {
74 f.allEnums = append(f.allEnums, m.Enums...)
75 f.allMessages = append(f.allMessages, m.Messages...)
76 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070077 })
Damien Neilce36f8d2018-09-13 15:19:08 -070078
Joe Tsai9667c482018-12-05 15:42:52 -080079 // Derive a reverse mapping of enum and message pointers to their index
80 // in allEnums and allMessages.
81 if len(f.allEnums) > 0 {
82 f.allEnumsByPtr = make(map[*protogen.Enum]int)
83 for i, e := range f.allEnums {
84 f.allEnumsByPtr[e] = i
85 }
86 }
87 if len(f.allMessages) > 0 {
88 f.allMessagesByPtr = make(map[*protogen.Message]int)
89 for i, m := range f.allMessages {
90 f.allMessagesByPtr[m] = i
91 }
92 }
Joe Tsaib6405bd2018-11-15 14:44:37 -080093
Damien Neil220c2022018-08-15 11:24:18 -070094 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070095 if f.Proto.GetOptions().GetDeprecated() {
96 g.P("// ", f.Desc.Path(), " is a deprecated file.")
97 } else {
98 g.P("// source: ", f.Desc.Path())
99 }
Damien Neil220c2022018-08-15 11:24:18 -0700100 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -0700101 g.PrintLeadingComments(protogen.Location{
102 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -0700103 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700104 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700105 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700106 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700107 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700108
Joe Tsai5d72cc22019-03-28 01:13:26 -0700109 // Emit a static check that enforces a minimum version of the proto package.
Joe Tsai58b42d82019-05-22 16:27:51 -0400110 g.P("const (")
111 g.P("// Verify that runtime/protoimpl is sufficiently up-to-date.")
112 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("MaxVersion"), " - ", protoimpl.Version, ")")
113 g.P("// Verify that this generated code is sufficiently up-to-date.")
114 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimpl.Version, " - ", protoimplPackage.Ident("MinVersion"), ")")
115 g.P(")")
Joe Tsai5d72cc22019-03-28 01:13:26 -0700116 g.P()
117
Damien Neil73ac8852018-09-17 15:11:24 -0700118 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
119 genImport(gen, g, f, imps.Get(i))
120 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700121 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700122 genEnum(gen, g, f, enum)
123 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700124 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700125 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700126 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700127 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700128
Joe Tsaib6405bd2018-11-15 14:44:37 -0800129 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800130
131 return g
Damien Neil7779e052018-09-07 14:14:06 -0700132}
133
Damien Neil73ac8852018-09-17 15:11:24 -0700134// walkMessages calls f on each message and all of its descendants.
135func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
136 for _, m := range messages {
137 f(m)
138 walkMessages(m.Messages, f)
139 }
140}
141
Damien Neild39efc82018-09-24 12:38:10 -0700142func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700143 impFile, ok := gen.FileByName(imp.Path())
144 if !ok {
145 return
146 }
147 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700148 // Don't generate imports or aliases for types in the same Go package.
149 return
150 }
Damien Neil40a08052018-10-29 09:07:41 -0700151 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700152 // referenced, because other code and tools depend on having the
153 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700154 if !imp.IsWeak {
155 g.Import(impFile.GoImportPath)
156 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700157 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700158 return
159 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800160
161 // Generate public imports by generating the imported file, parsing it,
162 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800163 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800164 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800165 b, err := impGen.Content()
166 if err != nil {
167 gen.Error(err)
168 return
169 }
170 fset := token.NewFileSet()
171 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
172 if err != nil {
173 gen.Error(err)
174 return
175 }
Damien Neila7cbd062019-01-06 16:29:14 -0800176 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800177 // Don't import unexported symbols.
178 r, _ := utf8.DecodeRuneInString(name)
179 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700180 return
181 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800182 // Don't import the FileDescriptor.
183 if name == impFile.GoDescriptorIdent.GoName {
184 return
185 }
Damien Neila7cbd062019-01-06 16:29:14 -0800186 // Don't import decls referencing a symbol defined in another package.
187 // i.e., don't import decls which are themselves public imports:
188 //
189 // type T = somepackage.T
190 if _, ok := expr.(*ast.SelectorExpr); ok {
191 return
192 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800193 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
194 }
195 g.P("// Symbols defined in public import of ", imp.Path())
196 g.P()
197 for _, decl := range astFile.Decls {
198 switch decl := decl.(type) {
199 case *ast.GenDecl:
200 for _, spec := range decl.Specs {
201 switch spec := spec.(type) {
202 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800203 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800204 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800205 for i, name := range spec.Names {
206 var expr ast.Expr
207 if i < len(spec.Values) {
208 expr = spec.Values[i]
209 }
210 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800211 }
212 case *ast.ImportSpec:
213 default:
214 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800215 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700216 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700217 }
Damien Neil6b541312018-10-29 09:14:14 -0700218 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700219 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700220}
221
Damien Neild39efc82018-09-24 12:38:10 -0700222func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Joe Tsai61968ce2019-04-01 12:59:24 -0700223 // Enum type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700224 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700225 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700226 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800227 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Joe Tsai61968ce2019-04-01 12:59:24 -0700228
229 // Enum value constants.
Damien Neil46abb572018-09-07 12:45:37 -0700230 g.P("const (")
231 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700232 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700233 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700234 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800235 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700236 }
237 g.P(")")
238 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800239
Joe Tsai61968ce2019-04-01 12:59:24 -0700240 // Enum value mapping (number -> name).
Joe Tsaiab61d412019-04-16 15:23:29 -0700241 if generateEnumMapVars {
242 nameMap := enum.GoIdent.GoName + "_name"
243 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
244 g.P("var ", nameMap, " = map[int32]string{")
245 generated := make(map[protoreflect.EnumNumber]bool)
246 for _, value := range enum.Values {
247 duplicate := ""
248 if _, present := generated[value.Desc.Number()]; present {
249 duplicate = "// Duplicate value: "
250 }
251 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
252 generated[value.Desc.Number()] = true
Damien Neil46abb572018-09-07 12:45:37 -0700253 }
Joe Tsaiab61d412019-04-16 15:23:29 -0700254 g.P("}")
255 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700256 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700257
Joe Tsai61968ce2019-04-01 12:59:24 -0700258 // Enum value mapping (name -> number).
Joe Tsaiab61d412019-04-16 15:23:29 -0700259 if generateEnumMapVars {
260 valueMap := enum.GoIdent.GoName + "_value"
261 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
262 g.P("var ", valueMap, " = map[string]int32{")
263 for _, value := range enum.Values {
264 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
265 }
266 g.P("}")
267 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700268 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700269
Joe Tsai61968ce2019-04-01 12:59:24 -0700270 // Enum method.
Joe Tsaidbab6c02019-05-14 15:06:03 -0700271 //
272 // NOTE: A pointer value is needed to represent presence in proto2.
273 // Since a proto2 message can reference a proto3 enum, it is useful to
274 // always generate this method (even on proto3 enums) to support that case.
275 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
276 g.P("p := new(", enum.GoIdent, ")")
277 g.P("*p = x")
278 g.P("return p")
279 g.P("}")
280 g.P()
281
Joe Tsai61968ce2019-04-01 12:59:24 -0700282 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700283 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700284 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700285 g.P("}")
286 g.P()
287
Joe Tsai61968ce2019-04-01 12:59:24 -0700288 genReflectEnum(gen, g, f, enum)
289
290 // UnmarshalJSON method.
Joe Tsai73903462018-12-14 12:22:41 -0800291 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700292 g.P("// Deprecated: Do not use.")
293 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700294 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700295 g.P("if err != nil {")
296 g.P("return err")
297 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700298 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700299 g.P("return nil")
300 g.P("}")
301 g.P()
302 }
303
Joe Tsai61968ce2019-04-01 12:59:24 -0700304 // EnumDescriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700305 if generateRawDescMethods {
306 var indexes []string
307 for i := 1; i < len(enum.Location.Path); i += 2 {
308 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
309 }
310 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
311 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
312 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
313 g.P("}")
314 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700315 }
Damien Neil46abb572018-09-07 12:45:37 -0700316
Damien Neilea7baf42018-09-28 14:23:44 -0700317 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700318}
319
Joe Tsai61968ce2019-04-01 12:59:24 -0700320// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700321//
322// Confusingly, this is <proto_package>.<go_ident>. This probably should have
323// been the full name of the proto enum type instead, but changing it at this
324// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700325func enumLegacyName(enum *protogen.Enum) string {
Joe Tsai67c1d9b2019-05-12 02:27:46 -0700326 fdesc := enum.Desc.ParentFile()
Damien Neildaa4fad2018-10-08 14:08:27 -0700327 if fdesc.Package() == "" {
328 return enum.GoIdent.GoName
329 }
Damien Neil658051b2018-09-10 12:26:21 -0700330 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
331}
332
Damien Neild39efc82018-09-24 12:38:10 -0700333func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700334 if message.Desc.IsMapEntry() {
335 return
336 }
337
Joe Tsai61968ce2019-04-01 12:59:24 -0700338 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700339 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800340 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700341 if hasComment {
342 g.P("//")
343 }
344 g.P(deprecationComment(true))
345 }
Damien Neil162c1272018-10-04 12:42:37 -0700346 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700347 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700348 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700349 if field.Oneof != nil {
Damien Neil1fa78d82018-09-13 13:12:36 -0700350 // It would be a bit simpler to iterate over the oneofs below,
351 // but generating the field here keeps the contents of the Go
352 // struct in the same order as the contents of the source
353 // .proto file.
Joe Tsaid24bc722019-04-15 23:39:09 -0700354 if field == field.Oneof.Fields[0] {
355 genOneofField(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700356 }
Damien Neil658051b2018-09-10 12:26:21 -0700357 continue
358 }
Damien Neilba1159f2018-10-17 12:53:18 -0700359 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700360 goType, pointer := fieldGoType(g, field)
361 if pointer {
362 goType = "*" + goType
363 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700364 tags := []string{
365 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
366 fmt.Sprintf("json:%q", fieldJSONTag(field)),
367 }
368 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700369 key := field.Message.Fields[0]
370 val := field.Message.Fields[1]
Damien Neil0bd5a382018-09-13 15:07:10 -0700371 tags = append(tags,
372 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
373 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
374 )
375 }
Damien Neil162c1272018-10-04 12:42:37 -0700376 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700377 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800378 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700379 }
380 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700381
382 if message.Desc.ExtensionRanges().Len() > 0 {
383 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800384 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700385 tags = append(tags, `protobuf_messageset:"1"`)
386 }
387 tags = append(tags, `json:"-"`)
Joe Tsai5e71dc92019-04-16 13:22:20 -0700388 g.P("XXX_InternalExtensions ", protoimplPackage.Ident("ExtensionFields"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700389 }
Joe Tsai5e71dc92019-04-16 13:22:20 -0700390 g.P("XXX_unrecognized ", protoimplPackage.Ident("UnknownFields"), " `json:\"-\"`")
391 g.P("XXX_sizecache ", protoimplPackage.Ident("SizeCache"), " `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700392 g.P("}")
393 g.P()
394
Joe Tsai61968ce2019-04-01 12:59:24 -0700395 // Reset method.
396 g.P("func (x *", message.GoIdent, ") Reset() {")
397 g.P("*x = ", message.GoIdent, "{}")
398 g.P("}")
399 g.P()
400 // String method.
401 g.P("func (x *", message.GoIdent, ") String() string {")
402 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
403 g.P("}")
404 g.P()
405 // ProtoMessage method.
406 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
407 g.P()
408
Joe Tsaib6405bd2018-11-15 14:44:37 -0800409 genReflectMessage(gen, g, f, message)
410
Joe Tsai61968ce2019-04-01 12:59:24 -0700411 // Descriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700412 if generateRawDescMethods {
413 var indexes []string
414 for i := 1; i < len(message.Location.Path); i += 2 {
415 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
416 }
417 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
418 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
419 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
420 g.P("}")
421 g.P()
Damien Neila1c6abc2018-09-12 13:36:34 -0700422 }
Damien Neil993c04d2018-09-14 15:41:11 -0700423
Joe Tsai61968ce2019-04-01 12:59:24 -0700424 // ExtensionRangeArray method.
Damien Neil993c04d2018-09-14 15:41:11 -0700425 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700426 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700427 extRangeVar := "extRange_" + message.GoIdent.GoName
428 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
429 for i := 0; i < extranges.Len(); i++ {
430 r := extranges.Get(i)
431 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
432 }
433 g.P("}")
434 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700435 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700436 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
437 g.P("return ", extRangeVar)
438 g.P("}")
439 g.P()
440 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700441
Damien Neilea7baf42018-09-28 14:23:44 -0700442 genWellKnownType(g, "*", message.GoIdent, message.Desc)
443
Damien Neilebc699d2018-09-13 08:50:13 -0700444 // Constants and vars holding the default values of fields.
445 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800446 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700447 continue
448 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700449 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700450 def := field.Desc.Default()
451 switch field.Desc.Kind() {
452 case protoreflect.StringKind:
453 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
454 case protoreflect.BytesKind:
455 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
456 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700457 evalueDesc := field.Desc.DefaultEnumValue()
Joe Tsaid24bc722019-04-15 23:39:09 -0700458 enum := field.Enum
Damien Neila485fbd2018-10-26 13:28:37 -0700459 evalue := enum.Values[evalueDesc.Index()]
Joe Tsaid24bc722019-04-15 23:39:09 -0700460 g.P("const ", defVarName, " ", field.Enum.GoIdent, " = ", evalue.GoIdent)
Damien Neilebc699d2018-09-13 08:50:13 -0700461 case protoreflect.FloatKind, protoreflect.DoubleKind:
462 // Floating point numbers need extra handling for -Inf/Inf/NaN.
463 f := field.Desc.Default().Float()
464 goType := "float64"
465 if field.Desc.Kind() == protoreflect.FloatKind {
466 goType = "float32"
467 }
468 // funcCall returns a call to a function in the math package,
469 // possibly converting the result to float32.
470 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800471 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700472 if goType != "float64" {
473 s = goType + "(" + s + ")"
474 }
475 return s
476 }
477 switch {
478 case math.IsInf(f, -1):
479 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
480 case math.IsInf(f, 1):
481 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
482 case math.IsNaN(f):
483 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
484 default:
Damien Neil982684b2018-09-28 14:12:41 -0700485 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700486 }
487 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700488 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700489 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
490 }
491 }
492 g.P()
493
Joe Tsai61968ce2019-04-01 12:59:24 -0700494 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700495 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700496 if isFirstOneofField(field) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700497 genOneofGetter(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700498 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700499 goType, pointer := fieldGoType(g, field)
500 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800501 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700502 g.P(deprecationComment(true))
503 }
Damien Neil162c1272018-10-04 12:42:37 -0700504 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700505 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Joe Tsaid24bc722019-04-15 23:39:09 -0700506 if field.Oneof != nil {
507 g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700508 g.P("return x.", field.GoName)
509 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700510 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700511 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700512 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700513 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700514 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700515 }
516 star := ""
517 if pointer {
518 star = "*"
519 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700520 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700521 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700522 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700523 g.P("return ", defaultValue)
524 g.P("}")
525 g.P()
526 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700527
Joe Tsai872b5002019-04-08 14:03:15 -0700528 // XXX_OneofWrappers method.
Damien Neil1fa78d82018-09-13 13:12:36 -0700529 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800530 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700531 }
Joe Tsai872b5002019-04-08 14:03:15 -0700532
533 // Oneof wrapper types.
534 for _, oneof := range message.Oneofs {
535 genOneofTypes(gen, g, f, message, oneof)
536 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700537}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700538
Damien Neil77f82fe2018-09-13 10:59:17 -0700539// fieldGoType returns the Go type used for a field.
540//
541// If it returns pointer=true, the struct field is a pointer to the type.
542func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700543 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700544 switch field.Desc.Kind() {
545 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700546 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700547 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700548 goType = g.QualifiedGoIdent(field.Enum.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700549 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700550 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700551 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700552 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700553 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700554 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700555 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700556 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700557 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700558 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700559 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700560 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700561 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700562 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700563 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700564 goType = "[]byte"
565 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700566 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700567 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700568 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700569 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700570 switch {
571 case field.Desc.IsList():
Damien Neil77f82fe2018-09-13 10:59:17 -0700572 goType = "[]" + goType
573 pointer = false
Joe Tsaiac31a352019-05-13 14:32:56 -0700574 case field.Desc.IsMap():
575 keyType, _ := fieldGoType(g, field.Message.Fields[0])
576 valType, _ := fieldGoType(g, field.Message.Fields[1])
577 return fmt.Sprintf("map[%v]%v", keyType, valType), false
Damien Neil658051b2018-09-10 12:26:21 -0700578 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700579
Damien Neil44000a12018-10-24 12:31:16 -0700580 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaiac31a352019-05-13 14:32:56 -0700581 if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700582 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700583 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700584 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700585}
586
587func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700588 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700589 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700590 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700591 }
Joe Tsai05828db2018-11-01 13:52:16 -0700592 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700593}
594
Damien Neil77f82fe2018-09-13 10:59:17 -0700595func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
Joe Tsaiac31a352019-05-13 14:32:56 -0700596 if field.Desc.IsList() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700597 return "nil"
598 }
Joe Tsai9667c482018-12-05 15:42:52 -0800599 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700600 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700601 if field.Desc.Kind() == protoreflect.BytesKind {
602 return "append([]byte(nil), " + defVarName + "...)"
603 }
604 return defVarName
605 }
606 switch field.Desc.Kind() {
607 case protoreflect.BoolKind:
608 return "false"
609 case protoreflect.StringKind:
610 return `""`
611 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
612 return "nil"
613 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700614 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700615 default:
616 return "0"
617 }
618}
619
Damien Neil658051b2018-09-10 12:26:21 -0700620func fieldJSONTag(field *protogen.Field) string {
621 return string(field.Desc.Name()) + ",omitempty"
622}
623
Joe Tsaiafb455e2019-03-14 16:08:22 -0700624func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
625 if len(f.allExtensions) == 0 {
626 return
Damien Neil154da982018-09-19 13:21:58 -0700627 }
628
Joe Tsaid8881392019-06-06 13:01:53 -0700629 g.P("var ", extDescsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700630 for _, extension := range f.allExtensions {
631 // Special case for proto2 message sets: If this extension is extending
632 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
633 // then drop that last component.
634 //
635 // TODO: This should be implemented in the text formatter rather than the generator.
636 // In addition, the situation for when to apply this special case is implemented
637 // differently in other languages:
638 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
639 name := extension.Desc.FullName()
640 if n, ok := isExtensionMessageSetElement(extension); ok {
641 name = n
642 }
643
644 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700645 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700646 goType, pointer := fieldGoType(g, extension)
647 if pointer {
648 goType = "*" + goType
649 }
650 g.P("ExtensionType: (", goType, ")(nil),")
651 g.P("Field: ", extension.Desc.Number(), ",")
652 g.P("Name: ", strconv.Quote(string(name)), ",")
653 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
654 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
655 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700656 }
Damien Neil993c04d2018-09-14 15:41:11 -0700657 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700658
659 g.P("var (")
660 for i, extension := range f.allExtensions {
661 ed := extension.Desc
Joe Tsaiac31a352019-05-13 14:32:56 -0700662 targetName := string(ed.ContainingMessage().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700663 typeName := ed.Kind().String()
664 switch ed.Kind() {
665 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700666 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700667 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700668 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700669 }
670 fieldName := string(ed.Name())
671 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
Joe Tsaid8881392019-06-06 13:01:53 -0700672 g.P(extensionVar(f.File, extension), " = &", extDescsVarName(f), "[", i, "]")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700673 g.P()
674 }
675 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700676}
677
Damien Neil62386962018-10-30 10:35:48 -0700678// isExtensionMessageSetELement returns the adjusted name of an extension
679// which extends proto2.bridge.MessageSet.
680func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700681 opts := extension.Extendee.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700682 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
683 return "", false
684 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700685 if extension.Parent == nil {
Damien Neil62386962018-10-30 10:35:48 -0700686 // This case shouldn't be given special handling at all--we're
687 // only supposed to drop the ".message_set_extension" for
688 // extensions defined within a message (i.e., the extension
689 // takes the message's name).
690 //
691 // This matches the behavior of the v1 generator, however.
692 //
693 // TODO: See if we can drop this case.
694 name = extension.Desc.FullName()
695 name = name[:len(name)-len("message_set_extension")]
696 return name, true
697 }
698 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700699}
700
Damien Neil993c04d2018-09-14 15:41:11 -0700701// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700702func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700703 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700704 if extension.Parent != nil {
705 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700706 }
707 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800708 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700709}
710
Damien Neil55fe1c02018-09-17 15:11:24 -0700711// deprecationComment returns a standard deprecation comment if deprecated is true.
712func deprecationComment(deprecated bool) string {
713 if !deprecated {
714 return ""
715 }
716 return "// Deprecated: Do not use."
717}
718
Damien Neil5c5b5312019-05-14 12:44:37 -0700719// TODO: Remove this. This was added to aid protojson, but protojson does this work
Joe Tsai61968ce2019-04-01 12:59:24 -0700720// through the use of protobuf reflection now.
Damien Neilea7baf42018-09-28 14:23:44 -0700721func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700722 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700723 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700724 g.P()
725 }
726}
727
728// Names of messages and enums for which we will generate XXX_WellKnownType methods.
729var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700730 "google.protobuf.Any": true,
731 "google.protobuf.Duration": true,
732 "google.protobuf.Empty": true,
733 "google.protobuf.Struct": true,
734 "google.protobuf.Timestamp": true,
735
736 "google.protobuf.BoolValue": true,
737 "google.protobuf.BytesValue": true,
738 "google.protobuf.DoubleValue": true,
739 "google.protobuf.FloatValue": true,
740 "google.protobuf.Int32Value": true,
741 "google.protobuf.Int64Value": true,
742 "google.protobuf.ListValue": true,
743 "google.protobuf.NullValue": true,
744 "google.protobuf.StringValue": true,
745 "google.protobuf.UInt32Value": true,
746 "google.protobuf.UInt64Value": true,
747 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700748}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800749
750// genOneofField generates the struct field for a oneof.
751func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
752 if g.PrintLeadingComments(oneof.Location) {
753 g.P("//")
754 }
755 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
756 for _, field := range oneof.Fields {
757 g.PrintLeadingComments(field.Location)
758 g.P("//\t*", fieldOneofType(field))
759 }
760 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
761 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
762}
763
Joe Tsai872b5002019-04-08 14:03:15 -0700764// genOneofGetter generate a Get method for a oneof.
765func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
766 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
767 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
768 g.P("if m != nil {")
769 g.P("return m.", oneofFieldName(oneof))
770 g.P("}")
771 g.P("return nil")
772 g.P("}")
773 g.P()
774}
775
776// genOneofWrappers generates the XXX_OneofWrappers method for a message.
777func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
778 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
779 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
780 g.P("return []interface{}{")
781 for _, oneof := range message.Oneofs {
782 for _, field := range oneof.Fields {
783 g.P("(*", fieldOneofType(field), ")(nil),")
784 }
785 }
786 g.P("}")
787 g.P("}")
788 g.P()
789}
790
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800791// genOneofTypes generates the interface type used for a oneof field,
792// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800793func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
794 ifName := oneofInterfaceName(oneof)
795 g.P("type ", ifName, " interface {")
796 g.P(ifName, "()")
797 g.P("}")
798 g.P()
799 for _, field := range oneof.Fields {
800 name := fieldOneofType(field)
801 g.Annotate(name.GoName, field.Location)
802 g.Annotate(name.GoName+"."+field.GoName, field.Location)
803 g.P("type ", name, " struct {")
804 goType, _ := fieldGoType(g, field)
805 tags := []string{
806 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
807 }
808 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
809 g.P("}")
810 g.P()
811 }
812 for _, field := range oneof.Fields {
813 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
814 g.P()
815 }
Joe Tsai872b5002019-04-08 14:03:15 -0700816}
817
818// isFirstOneofField reports whether this is the first field in a oneof.
819func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700820 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800821}
822
823// oneofFieldName returns the name of the struct field holding the oneof value.
824//
825// This function is trivial, but pulling out the name like this makes it easier
826// to experiment with alternative oneof implementations.
827func oneofFieldName(oneof *protogen.Oneof) string {
828 return oneof.GoName
829}
830
831// oneofInterfaceName returns the name of the interface type implemented by
832// the oneof field value types.
833func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700834 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800835}
836
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800837// fieldOneofType returns the wrapper type used to represent a field in a oneof.
838func fieldOneofType(field *protogen.Field) protogen.GoIdent {
839 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700840 GoImportPath: field.Parent.GoIdent.GoImportPath,
841 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800842 }
843 // Check for collisions with nested messages or enums.
844 //
845 // This conflict resolution is incomplete: Among other things, it
846 // does not consider collisions with other oneof field types.
847 //
848 // TODO: Consider dropping this entirely. Detecting conflicts and
849 // producing an error is almost certainly better than permuting
850 // field and type names in mostly unpredictable ways.
851Loop:
852 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700853 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800854 if message.GoIdent == ident {
855 ident.GoName += "_"
856 continue Loop
857 }
858 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700859 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800860 if enum.GoIdent == ident {
861 ident.GoName += "_"
862 continue Loop
863 }
864 }
865 return ident
866 }
867}