blob: 3cd0c3894c6c4bbe17805e85ff008dc90d2c7353 [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
Joe Tsai09912272019-07-08 10:38:11 -070038
39 // generateOneofWrapperMethods specifies whether to generate
40 // XXX_OneofWrappers methods on messages with oneofs.
41 generateOneofWrapperMethods = false
Joe Tsaiab61d412019-04-16 15:23:29 -070042)
43
44const (
Joe Tsai5d72cc22019-03-28 01:13:26 -070045 syncPackage = protogen.GoImportPath("sync")
Joe Tsai4fddeba2019-03-20 18:29:32 -070046 mathPackage = protogen.GoImportPath("math")
Damien Neile89e6242019-05-13 23:55:40 -070047 protoifacePackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoiface")
48 protoimplPackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoimpl")
49 protoreflectPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoreflect")
50 protoregistryPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoregistry")
Joe Tsaid8881392019-06-06 13:01:53 -070051 prototypePackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/prototype")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080052)
Damien Neil46abb572018-09-07 12:45:37 -070053
Damien Neild39efc82018-09-24 12:38:10 -070054type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070055 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080056
Joe Tsai9667c482018-12-05 15:42:52 -080057 allEnums []*protogen.Enum
58 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
59 allMessages []*protogen.Message
60 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
61 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070062}
63
Damien Neil9c420a62018-09-27 15:26:33 -070064// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080065func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
66 filename := file.GeneratedFilenamePrefix + ".pb.go"
67 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070068 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070069 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070070 }
71
Damien Neil8012b442019-01-18 09:32:24 -080072 // Collect all enums, messages, and extensions in "flattened ordering".
Joe Tsaid8881392019-06-06 13:01:53 -070073 // See filetype.TypeBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080074 f.allEnums = append(f.allEnums, f.Enums...)
75 f.allMessages = append(f.allMessages, f.Messages...)
76 f.allExtensions = append(f.allExtensions, f.Extensions...)
77 walkMessages(f.Messages, func(m *protogen.Message) {
78 f.allEnums = append(f.allEnums, m.Enums...)
79 f.allMessages = append(f.allMessages, m.Messages...)
80 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070081 })
Damien Neilce36f8d2018-09-13 15:19:08 -070082
Joe Tsai9667c482018-12-05 15:42:52 -080083 // Derive a reverse mapping of enum and message pointers to their index
84 // in allEnums and allMessages.
85 if len(f.allEnums) > 0 {
86 f.allEnumsByPtr = make(map[*protogen.Enum]int)
87 for i, e := range f.allEnums {
88 f.allEnumsByPtr[e] = i
89 }
90 }
91 if len(f.allMessages) > 0 {
92 f.allMessagesByPtr = make(map[*protogen.Message]int)
93 for i, m := range f.allMessages {
94 f.allMessagesByPtr[m] = i
95 }
96 }
Joe Tsaib6405bd2018-11-15 14:44:37 -080097
Damien Neil220c2022018-08-15 11:24:18 -070098 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070099 if f.Proto.GetOptions().GetDeprecated() {
100 g.P("// ", f.Desc.Path(), " is a deprecated file.")
101 } else {
102 g.P("// source: ", f.Desc.Path())
103 }
Damien Neil220c2022018-08-15 11:24:18 -0700104 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -0700105 g.PrintLeadingComments(protogen.Location{
106 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -0700107 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700108 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700109 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700110 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700111 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700112
Joe Tsai5d72cc22019-03-28 01:13:26 -0700113 // Emit a static check that enforces a minimum version of the proto package.
Joe Tsai58b42d82019-05-22 16:27:51 -0400114 g.P("const (")
115 g.P("// Verify that runtime/protoimpl is sufficiently up-to-date.")
116 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("MaxVersion"), " - ", protoimpl.Version, ")")
117 g.P("// Verify that this generated code is sufficiently up-to-date.")
118 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimpl.Version, " - ", protoimplPackage.Ident("MinVersion"), ")")
119 g.P(")")
Joe Tsai5d72cc22019-03-28 01:13:26 -0700120 g.P()
121
Damien Neil73ac8852018-09-17 15:11:24 -0700122 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
123 genImport(gen, g, f, imps.Get(i))
124 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700125 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700126 genEnum(gen, g, f, enum)
127 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700128 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700129 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700130 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700131 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700132
Joe Tsaib6405bd2018-11-15 14:44:37 -0800133 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800134
135 return g
Damien Neil7779e052018-09-07 14:14:06 -0700136}
137
Damien Neil73ac8852018-09-17 15:11:24 -0700138// walkMessages calls f on each message and all of its descendants.
139func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
140 for _, m := range messages {
141 f(m)
142 walkMessages(m.Messages, f)
143 }
144}
145
Damien Neild39efc82018-09-24 12:38:10 -0700146func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700147 impFile, ok := gen.FileByName(imp.Path())
148 if !ok {
149 return
150 }
151 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700152 // Don't generate imports or aliases for types in the same Go package.
153 return
154 }
Damien Neil40a08052018-10-29 09:07:41 -0700155 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700156 // referenced, because other code and tools depend on having the
157 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700158 if !imp.IsWeak {
159 g.Import(impFile.GoImportPath)
160 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700161 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700162 return
163 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800164
165 // Generate public imports by generating the imported file, parsing it,
166 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800167 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800168 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800169 b, err := impGen.Content()
170 if err != nil {
171 gen.Error(err)
172 return
173 }
174 fset := token.NewFileSet()
175 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
176 if err != nil {
177 gen.Error(err)
178 return
179 }
Damien Neila7cbd062019-01-06 16:29:14 -0800180 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800181 // Don't import unexported symbols.
182 r, _ := utf8.DecodeRuneInString(name)
183 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700184 return
185 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800186 // Don't import the FileDescriptor.
187 if name == impFile.GoDescriptorIdent.GoName {
188 return
189 }
Damien Neila7cbd062019-01-06 16:29:14 -0800190 // Don't import decls referencing a symbol defined in another package.
191 // i.e., don't import decls which are themselves public imports:
192 //
193 // type T = somepackage.T
194 if _, ok := expr.(*ast.SelectorExpr); ok {
195 return
196 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800197 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
198 }
199 g.P("// Symbols defined in public import of ", imp.Path())
200 g.P()
201 for _, decl := range astFile.Decls {
202 switch decl := decl.(type) {
203 case *ast.GenDecl:
204 for _, spec := range decl.Specs {
205 switch spec := spec.(type) {
206 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800207 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800208 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800209 for i, name := range spec.Names {
210 var expr ast.Expr
211 if i < len(spec.Values) {
212 expr = spec.Values[i]
213 }
214 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800215 }
216 case *ast.ImportSpec:
217 default:
218 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800219 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700220 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700221 }
Damien Neil6b541312018-10-29 09:14:14 -0700222 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700223 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700224}
225
Damien Neild39efc82018-09-24 12:38:10 -0700226func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Joe Tsai61968ce2019-04-01 12:59:24 -0700227 // Enum type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700228 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700229 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700230 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800231 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Joe Tsai61968ce2019-04-01 12:59:24 -0700232
233 // Enum value constants.
Damien Neil46abb572018-09-07 12:45:37 -0700234 g.P("const (")
235 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700236 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700237 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700238 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800239 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700240 }
241 g.P(")")
242 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800243
Joe Tsai61968ce2019-04-01 12:59:24 -0700244 // Enum value mapping (number -> name).
Joe Tsaiab61d412019-04-16 15:23:29 -0700245 if generateEnumMapVars {
246 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsaiab61d412019-04-16 15:23:29 -0700247 g.P("var ", nameMap, " = map[int32]string{")
248 generated := make(map[protoreflect.EnumNumber]bool)
249 for _, value := range enum.Values {
250 duplicate := ""
251 if _, present := generated[value.Desc.Number()]; present {
252 duplicate = "// Duplicate value: "
253 }
254 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
255 generated[value.Desc.Number()] = true
Damien Neil46abb572018-09-07 12:45:37 -0700256 }
Joe Tsaiab61d412019-04-16 15:23:29 -0700257 g.P("}")
258 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700259 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700260
Joe Tsai61968ce2019-04-01 12:59:24 -0700261 // Enum value mapping (name -> number).
Joe Tsaiab61d412019-04-16 15:23:29 -0700262 if generateEnumMapVars {
263 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsaiab61d412019-04-16 15:23:29 -0700264 g.P("var ", valueMap, " = map[string]int32{")
265 for _, value := range enum.Values {
266 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
267 }
268 g.P("}")
269 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700270 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700271
Joe Tsai61968ce2019-04-01 12:59:24 -0700272 // Enum method.
Joe Tsaidbab6c02019-05-14 15:06:03 -0700273 //
274 // NOTE: A pointer value is needed to represent presence in proto2.
275 // Since a proto2 message can reference a proto3 enum, it is useful to
276 // always generate this method (even on proto3 enums) to support that case.
277 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
278 g.P("p := new(", enum.GoIdent, ")")
279 g.P("*p = x")
280 g.P("return p")
281 g.P("}")
282 g.P()
283
Joe Tsai61968ce2019-04-01 12:59:24 -0700284 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700285 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700286 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700287 g.P("}")
288 g.P()
289
Joe Tsai61968ce2019-04-01 12:59:24 -0700290 genReflectEnum(gen, g, f, enum)
291
292 // UnmarshalJSON method.
Joe Tsai73903462018-12-14 12:22:41 -0800293 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700294 g.P("// Deprecated: Do not use.")
295 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700296 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700297 g.P("if err != nil {")
298 g.P("return err")
299 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700300 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700301 g.P("return nil")
302 g.P("}")
303 g.P()
304 }
305
Joe Tsai61968ce2019-04-01 12:59:24 -0700306 // EnumDescriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700307 if generateRawDescMethods {
308 var indexes []string
309 for i := 1; i < len(enum.Location.Path); i += 2 {
310 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
311 }
312 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
313 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
314 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
315 g.P("}")
316 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700317 }
Damien Neil46abb572018-09-07 12:45:37 -0700318
Damien Neilea7baf42018-09-28 14:23:44 -0700319 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700320}
321
Joe Tsai61968ce2019-04-01 12:59:24 -0700322// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700323//
324// Confusingly, this is <proto_package>.<go_ident>. This probably should have
325// been the full name of the proto enum type instead, but changing it at this
326// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700327func enumLegacyName(enum *protogen.Enum) string {
Joe Tsai67c1d9b2019-05-12 02:27:46 -0700328 fdesc := enum.Desc.ParentFile()
Damien Neildaa4fad2018-10-08 14:08:27 -0700329 if fdesc.Package() == "" {
330 return enum.GoIdent.GoName
331 }
Damien Neil658051b2018-09-10 12:26:21 -0700332 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
333}
334
Damien Neild39efc82018-09-24 12:38:10 -0700335func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700336 if message.Desc.IsMapEntry() {
337 return
338 }
339
Joe Tsai61968ce2019-04-01 12:59:24 -0700340 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700341 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800342 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700343 if hasComment {
344 g.P("//")
345 }
346 g.P(deprecationComment(true))
347 }
Damien Neil162c1272018-10-04 12:42:37 -0700348 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700349 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700350 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700351 if field.Oneof != nil {
Damien Neil1fa78d82018-09-13 13:12:36 -0700352 // It would be a bit simpler to iterate over the oneofs below,
353 // but generating the field here keeps the contents of the Go
354 // struct in the same order as the contents of the source
355 // .proto file.
Joe Tsaid24bc722019-04-15 23:39:09 -0700356 if field == field.Oneof.Fields[0] {
357 genOneofField(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700358 }
Damien Neil658051b2018-09-10 12:26:21 -0700359 continue
360 }
Damien Neilba1159f2018-10-17 12:53:18 -0700361 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700362 goType, pointer := fieldGoType(g, field)
363 if pointer {
364 goType = "*" + goType
365 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700366 tags := []string{
367 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
368 fmt.Sprintf("json:%q", fieldJSONTag(field)),
369 }
370 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700371 key := field.Message.Fields[0]
372 val := field.Message.Fields[1]
Damien Neil0bd5a382018-09-13 15:07:10 -0700373 tags = append(tags,
374 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
375 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
376 )
377 }
Damien Neil162c1272018-10-04 12:42:37 -0700378 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700379 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800380 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700381 }
382 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700383
384 if message.Desc.ExtensionRanges().Len() > 0 {
385 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800386 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700387 tags = append(tags, `protobuf_messageset:"1"`)
388 }
389 tags = append(tags, `json:"-"`)
Joe Tsai5e71dc92019-04-16 13:22:20 -0700390 g.P("XXX_InternalExtensions ", protoimplPackage.Ident("ExtensionFields"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700391 }
Joe Tsai5e71dc92019-04-16 13:22:20 -0700392 g.P("XXX_unrecognized ", protoimplPackage.Ident("UnknownFields"), " `json:\"-\"`")
393 g.P("XXX_sizecache ", protoimplPackage.Ident("SizeCache"), " `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700394 g.P("}")
395 g.P()
396
Joe Tsai61968ce2019-04-01 12:59:24 -0700397 // Reset method.
398 g.P("func (x *", message.GoIdent, ") Reset() {")
399 g.P("*x = ", message.GoIdent, "{}")
400 g.P("}")
401 g.P()
402 // String method.
403 g.P("func (x *", message.GoIdent, ") String() string {")
404 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
405 g.P("}")
406 g.P()
407 // ProtoMessage method.
408 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
409 g.P()
410
Joe Tsaib6405bd2018-11-15 14:44:37 -0800411 genReflectMessage(gen, g, f, message)
412
Joe Tsai61968ce2019-04-01 12:59:24 -0700413 // Descriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700414 if generateRawDescMethods {
415 var indexes []string
416 for i := 1; i < len(message.Location.Path); i += 2 {
417 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
418 }
419 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
420 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
421 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
422 g.P("}")
423 g.P()
Damien Neila1c6abc2018-09-12 13:36:34 -0700424 }
Damien Neil993c04d2018-09-14 15:41:11 -0700425
Joe Tsai61968ce2019-04-01 12:59:24 -0700426 // ExtensionRangeArray method.
Damien Neil993c04d2018-09-14 15:41:11 -0700427 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700428 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700429 extRangeVar := "extRange_" + message.GoIdent.GoName
430 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
431 for i := 0; i < extranges.Len(); i++ {
432 r := extranges.Get(i)
433 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
434 }
435 g.P("}")
436 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700437 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700438 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
439 g.P("return ", extRangeVar)
440 g.P("}")
441 g.P()
442 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700443
Damien Neilea7baf42018-09-28 14:23:44 -0700444 genWellKnownType(g, "*", message.GoIdent, message.Desc)
445
Damien Neilebc699d2018-09-13 08:50:13 -0700446 // Constants and vars holding the default values of fields.
447 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800448 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700449 continue
450 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700451 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700452 def := field.Desc.Default()
453 switch field.Desc.Kind() {
454 case protoreflect.StringKind:
455 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
456 case protoreflect.BytesKind:
457 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
458 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700459 evalueDesc := field.Desc.DefaultEnumValue()
Joe Tsaid24bc722019-04-15 23:39:09 -0700460 enum := field.Enum
Damien Neila485fbd2018-10-26 13:28:37 -0700461 evalue := enum.Values[evalueDesc.Index()]
Joe Tsaid24bc722019-04-15 23:39:09 -0700462 g.P("const ", defVarName, " ", field.Enum.GoIdent, " = ", evalue.GoIdent)
Damien Neilebc699d2018-09-13 08:50:13 -0700463 case protoreflect.FloatKind, protoreflect.DoubleKind:
464 // Floating point numbers need extra handling for -Inf/Inf/NaN.
465 f := field.Desc.Default().Float()
466 goType := "float64"
467 if field.Desc.Kind() == protoreflect.FloatKind {
468 goType = "float32"
469 }
470 // funcCall returns a call to a function in the math package,
471 // possibly converting the result to float32.
472 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800473 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700474 if goType != "float64" {
475 s = goType + "(" + s + ")"
476 }
477 return s
478 }
479 switch {
480 case math.IsInf(f, -1):
481 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
482 case math.IsInf(f, 1):
483 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
484 case math.IsNaN(f):
485 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
486 default:
Damien Neil982684b2018-09-28 14:12:41 -0700487 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700488 }
489 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700490 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700491 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
492 }
493 }
494 g.P()
495
Joe Tsai61968ce2019-04-01 12:59:24 -0700496 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700497 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700498 if isFirstOneofField(field) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700499 genOneofGetter(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700500 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700501 goType, pointer := fieldGoType(g, field)
502 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800503 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700504 g.P(deprecationComment(true))
505 }
Damien Neil162c1272018-10-04 12:42:37 -0700506 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700507 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Joe Tsaid24bc722019-04-15 23:39:09 -0700508 if field.Oneof != nil {
509 g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700510 g.P("return x.", field.GoName)
511 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700512 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700513 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700514 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700515 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700516 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700517 }
518 star := ""
519 if pointer {
520 star = "*"
521 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700522 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700523 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700524 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700525 g.P("return ", defaultValue)
526 g.P("}")
527 g.P()
528 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700529
Joe Tsai09912272019-07-08 10:38:11 -0700530 // Oneof wrapper types.
Damien Neil1fa78d82018-09-13 13:12:36 -0700531 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800532 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700533 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700534}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700535
Damien Neil77f82fe2018-09-13 10:59:17 -0700536// fieldGoType returns the Go type used for a field.
537//
538// If it returns pointer=true, the struct field is a pointer to the type.
539func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700540 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700541 switch field.Desc.Kind() {
542 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700543 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700544 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700545 goType = g.QualifiedGoIdent(field.Enum.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700546 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700547 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700548 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700549 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700550 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700551 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700552 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700553 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700554 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700555 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700556 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700557 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700558 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700559 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700560 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700561 goType = "[]byte"
562 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700563 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700564 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700565 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700566 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700567 switch {
568 case field.Desc.IsList():
Damien Neil77f82fe2018-09-13 10:59:17 -0700569 goType = "[]" + goType
570 pointer = false
Joe Tsaiac31a352019-05-13 14:32:56 -0700571 case field.Desc.IsMap():
572 keyType, _ := fieldGoType(g, field.Message.Fields[0])
573 valType, _ := fieldGoType(g, field.Message.Fields[1])
574 return fmt.Sprintf("map[%v]%v", keyType, valType), false
Damien Neil658051b2018-09-10 12:26:21 -0700575 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700576
Damien Neil44000a12018-10-24 12:31:16 -0700577 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaiac31a352019-05-13 14:32:56 -0700578 if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700579 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700580 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700581 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700582}
583
584func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700585 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700586 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700587 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700588 }
Joe Tsai05828db2018-11-01 13:52:16 -0700589 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700590}
591
Damien Neil77f82fe2018-09-13 10:59:17 -0700592func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
Joe Tsaiac31a352019-05-13 14:32:56 -0700593 if field.Desc.IsList() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700594 return "nil"
595 }
Joe Tsai9667c482018-12-05 15:42:52 -0800596 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700597 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700598 if field.Desc.Kind() == protoreflect.BytesKind {
599 return "append([]byte(nil), " + defVarName + "...)"
600 }
601 return defVarName
602 }
603 switch field.Desc.Kind() {
604 case protoreflect.BoolKind:
605 return "false"
606 case protoreflect.StringKind:
607 return `""`
608 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
609 return "nil"
610 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700611 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700612 default:
613 return "0"
614 }
615}
616
Damien Neil658051b2018-09-10 12:26:21 -0700617func fieldJSONTag(field *protogen.Field) string {
618 return string(field.Desc.Name()) + ",omitempty"
619}
620
Joe Tsaiafb455e2019-03-14 16:08:22 -0700621func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
622 if len(f.allExtensions) == 0 {
623 return
Damien Neil154da982018-09-19 13:21:58 -0700624 }
625
Joe Tsaid8881392019-06-06 13:01:53 -0700626 g.P("var ", extDescsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700627 for _, extension := range f.allExtensions {
628 // Special case for proto2 message sets: If this extension is extending
629 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
630 // then drop that last component.
631 //
632 // TODO: This should be implemented in the text formatter rather than the generator.
633 // In addition, the situation for when to apply this special case is implemented
634 // differently in other languages:
635 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
636 name := extension.Desc.FullName()
637 if n, ok := isExtensionMessageSetElement(extension); ok {
638 name = n
639 }
640
641 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700642 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700643 goType, pointer := fieldGoType(g, extension)
644 if pointer {
645 goType = "*" + goType
646 }
647 g.P("ExtensionType: (", goType, ")(nil),")
648 g.P("Field: ", extension.Desc.Number(), ",")
649 g.P("Name: ", strconv.Quote(string(name)), ",")
650 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
651 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
652 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700653 }
Damien Neil993c04d2018-09-14 15:41:11 -0700654 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700655
656 g.P("var (")
657 for i, extension := range f.allExtensions {
658 ed := extension.Desc
Joe Tsaiac31a352019-05-13 14:32:56 -0700659 targetName := string(ed.ContainingMessage().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700660 typeName := ed.Kind().String()
661 switch ed.Kind() {
662 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700663 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700664 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700665 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700666 }
667 fieldName := string(ed.Name())
668 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
Joe Tsaid8881392019-06-06 13:01:53 -0700669 g.P(extensionVar(f.File, extension), " = &", extDescsVarName(f), "[", i, "]")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700670 g.P()
671 }
672 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700673}
674
Damien Neil62386962018-10-30 10:35:48 -0700675// isExtensionMessageSetELement returns the adjusted name of an extension
676// which extends proto2.bridge.MessageSet.
677func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700678 opts := extension.Extendee.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700679 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
680 return "", false
681 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700682 if extension.Parent == nil {
Damien Neil62386962018-10-30 10:35:48 -0700683 // This case shouldn't be given special handling at all--we're
684 // only supposed to drop the ".message_set_extension" for
685 // extensions defined within a message (i.e., the extension
686 // takes the message's name).
687 //
688 // This matches the behavior of the v1 generator, however.
689 //
690 // TODO: See if we can drop this case.
691 name = extension.Desc.FullName()
692 name = name[:len(name)-len("message_set_extension")]
693 return name, true
694 }
695 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700696}
697
Damien Neil993c04d2018-09-14 15:41:11 -0700698// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700699func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700700 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700701 if extension.Parent != nil {
702 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700703 }
704 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800705 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700706}
707
Damien Neil55fe1c02018-09-17 15:11:24 -0700708// deprecationComment returns a standard deprecation comment if deprecated is true.
709func deprecationComment(deprecated bool) string {
710 if !deprecated {
711 return ""
712 }
713 return "// Deprecated: Do not use."
714}
715
Damien Neil5c5b5312019-05-14 12:44:37 -0700716// TODO: Remove this. This was added to aid protojson, but protojson does this work
Joe Tsai61968ce2019-04-01 12:59:24 -0700717// through the use of protobuf reflection now.
Damien Neilea7baf42018-09-28 14:23:44 -0700718func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700719 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700720 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700721 g.P()
722 }
723}
724
725// Names of messages and enums for which we will generate XXX_WellKnownType methods.
726var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700727 "google.protobuf.Any": true,
728 "google.protobuf.Duration": true,
729 "google.protobuf.Empty": true,
730 "google.protobuf.Struct": true,
731 "google.protobuf.Timestamp": true,
732
733 "google.protobuf.BoolValue": true,
734 "google.protobuf.BytesValue": true,
735 "google.protobuf.DoubleValue": true,
736 "google.protobuf.FloatValue": true,
737 "google.protobuf.Int32Value": true,
738 "google.protobuf.Int64Value": true,
739 "google.protobuf.ListValue": true,
740 "google.protobuf.NullValue": true,
741 "google.protobuf.StringValue": true,
742 "google.protobuf.UInt32Value": true,
743 "google.protobuf.UInt64Value": true,
744 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700745}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800746
747// genOneofField generates the struct field for a oneof.
748func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
749 if g.PrintLeadingComments(oneof.Location) {
750 g.P("//")
751 }
752 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
753 for _, field := range oneof.Fields {
754 g.PrintLeadingComments(field.Location)
755 g.P("//\t*", fieldOneofType(field))
756 }
757 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
758 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
759}
760
Joe Tsai872b5002019-04-08 14:03:15 -0700761// genOneofGetter generate a Get method for a oneof.
762func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
763 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
764 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
765 g.P("if m != nil {")
766 g.P("return m.", oneofFieldName(oneof))
767 g.P("}")
768 g.P("return nil")
769 g.P("}")
770 g.P()
771}
772
Joe Tsai09912272019-07-08 10:38:11 -0700773// genOneofWrappers generates the oneof wrapper types and associates the types
774// with the parent message type.
Joe Tsai872b5002019-04-08 14:03:15 -0700775func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Joe Tsai09912272019-07-08 10:38:11 -0700776 idx := f.allMessagesByPtr[message]
777 typesVar := messageTypesVarName(f)
778
779 // Associate the wrapper types through a XXX_OneofWrappers method.
780 if generateOneofWrapperMethods {
781 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
782 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
783 g.P("return ", typesVar, "[", idx, "].OneofWrappers")
784 g.P("}")
785 g.P()
Joe Tsai872b5002019-04-08 14:03:15 -0700786 }
Joe Tsai09912272019-07-08 10:38:11 -0700787
788 // Generate the oneof wrapper types.
789 for _, oneof := range message.Oneofs {
790 genOneofTypes(gen, g, f, message, oneof)
791 }
Joe Tsai872b5002019-04-08 14:03:15 -0700792}
793
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800794// genOneofTypes generates the interface type used for a oneof field,
795// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800796func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
797 ifName := oneofInterfaceName(oneof)
798 g.P("type ", ifName, " interface {")
799 g.P(ifName, "()")
800 g.P("}")
801 g.P()
802 for _, field := range oneof.Fields {
803 name := fieldOneofType(field)
804 g.Annotate(name.GoName, field.Location)
805 g.Annotate(name.GoName+"."+field.GoName, field.Location)
806 g.P("type ", name, " struct {")
807 goType, _ := fieldGoType(g, field)
808 tags := []string{
809 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
810 }
811 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
812 g.P("}")
813 g.P()
814 }
815 for _, field := range oneof.Fields {
816 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
817 g.P()
818 }
Joe Tsai872b5002019-04-08 14:03:15 -0700819}
820
821// isFirstOneofField reports whether this is the first field in a oneof.
822func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700823 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800824}
825
826// oneofFieldName returns the name of the struct field holding the oneof value.
827//
828// This function is trivial, but pulling out the name like this makes it easier
829// to experiment with alternative oneof implementations.
830func oneofFieldName(oneof *protogen.Oneof) string {
831 return oneof.GoName
832}
833
834// oneofInterfaceName returns the name of the interface type implemented by
835// the oneof field value types.
836func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700837 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800838}
839
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800840// fieldOneofType returns the wrapper type used to represent a field in a oneof.
841func fieldOneofType(field *protogen.Field) protogen.GoIdent {
842 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700843 GoImportPath: field.Parent.GoIdent.GoImportPath,
844 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800845 }
846 // Check for collisions with nested messages or enums.
847 //
848 // This conflict resolution is incomplete: Among other things, it
849 // does not consider collisions with other oneof field types.
850 //
851 // TODO: Consider dropping this entirely. Detecting conflicts and
852 // producing an error is almost certainly better than permuting
853 // field and type names in mostly unpredictable ways.
854Loop:
855 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700856 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800857 if message.GoIdent == ident {
858 ident.GoName += "_"
859 continue Loop
860 }
861 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700862 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800863 if enum.GoIdent == ident {
864 ident.GoName += "_"
865 continue Loop
866 }
867 }
868 return ident
869 }
870}