blob: 47c47aa3cde18446adee925d2190b513f4f68064 [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 Tsaic0e4bb22019-07-06 13:05:11 -070042
Joe Tsai5455ef52019-07-08 13:49:48 -070043 // generateWKTMarkerMethods specifes whether to generate
44 // XXX_WellKnownType methods on well-known types.
45 generateWKTMarkerMethods = false
46
Joe Tsaic0e4bb22019-07-06 13:05:11 -070047 // generateNoUnkeyedLiteralFields specifies whether to generate
48 // the XXX_NoUnkeyedLiteral field.
49 generateNoUnkeyedLiteralFields = false
50
51 // generateExportedSizeCacheFields specifies whether to generate an exported
52 // XXX_sizecache field instead of an unexported sizeCache field.
53 generateExportedSizeCacheFields = false
54
55 // generateExportedUnknownFields specifies whether to generate an exported
56 // XXX_unrecognized field instead of an unexported unknownFields field.
57 generateExportedUnknownFields = false
58
59 // generateExportedExtensionFields specifies whether to generate an exported
60 // XXX_InternalExtensions field instead of an unexported extensionFields field.
61 generateExportedExtensionFields = false
Joe Tsaiab61d412019-04-16 15:23:29 -070062)
63
64const (
Joe Tsai5d72cc22019-03-28 01:13:26 -070065 syncPackage = protogen.GoImportPath("sync")
Joe Tsai4fddeba2019-03-20 18:29:32 -070066 mathPackage = protogen.GoImportPath("math")
Damien Neile89e6242019-05-13 23:55:40 -070067 protoifacePackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoiface")
68 protoimplPackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoimpl")
69 protoreflectPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoreflect")
70 protoregistryPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoregistry")
Joe Tsaid8881392019-06-06 13:01:53 -070071 prototypePackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/prototype")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080072)
Damien Neil46abb572018-09-07 12:45:37 -070073
Damien Neild39efc82018-09-24 12:38:10 -070074type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070075 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080076
Joe Tsaic0e4bb22019-07-06 13:05:11 -070077 allEnums []*protogen.Enum
78 allMessages []*protogen.Message
79 allExtensions []*protogen.Extension
80
81 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
82 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
83 allMessageFieldsByPtr map[*protogen.Message]*structFields
84}
85
86type structFields struct {
87 count int
88 unexported map[int]string
89}
90
91func (sf *structFields) append(name string) {
92 if r, _ := utf8.DecodeRuneInString(name); !unicode.IsUpper(r) {
93 if sf.unexported == nil {
94 sf.unexported = make(map[int]string)
95 }
96 sf.unexported[sf.count] = name
97 }
98 sf.count++
Damien Neilcab8dfe2018-09-06 14:51:28 -070099}
100
Damien Neil9c420a62018-09-27 15:26:33 -0700101// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -0800102func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
103 filename := file.GeneratedFilenamePrefix + ".pb.go"
104 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -0700105 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -0700106 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -0700107 }
108
Damien Neil8012b442019-01-18 09:32:24 -0800109 // Collect all enums, messages, and extensions in "flattened ordering".
Joe Tsaid8881392019-06-06 13:01:53 -0700110 // See filetype.TypeBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -0800111 f.allEnums = append(f.allEnums, f.Enums...)
112 f.allMessages = append(f.allMessages, f.Messages...)
113 f.allExtensions = append(f.allExtensions, f.Extensions...)
114 walkMessages(f.Messages, func(m *protogen.Message) {
115 f.allEnums = append(f.allEnums, m.Enums...)
116 f.allMessages = append(f.allMessages, m.Messages...)
117 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -0700118 })
Damien Neilce36f8d2018-09-13 15:19:08 -0700119
Joe Tsai9667c482018-12-05 15:42:52 -0800120 // Derive a reverse mapping of enum and message pointers to their index
121 // in allEnums and allMessages.
122 if len(f.allEnums) > 0 {
123 f.allEnumsByPtr = make(map[*protogen.Enum]int)
124 for i, e := range f.allEnums {
125 f.allEnumsByPtr[e] = i
126 }
127 }
128 if len(f.allMessages) > 0 {
129 f.allMessagesByPtr = make(map[*protogen.Message]int)
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700130 f.allMessageFieldsByPtr = make(map[*protogen.Message]*structFields)
Joe Tsai9667c482018-12-05 15:42:52 -0800131 for i, m := range f.allMessages {
132 f.allMessagesByPtr[m] = i
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700133 f.allMessageFieldsByPtr[m] = new(structFields)
Joe Tsai9667c482018-12-05 15:42:52 -0800134 }
135 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800136
Damien Neil220c2022018-08-15 11:24:18 -0700137 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700138 if f.Proto.GetOptions().GetDeprecated() {
139 g.P("// ", f.Desc.Path(), " is a deprecated file.")
140 } else {
141 g.P("// source: ", f.Desc.Path())
142 }
Damien Neil220c2022018-08-15 11:24:18 -0700143 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -0700144 g.PrintLeadingComments(protogen.Location{
145 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -0700146 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700147 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700148 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700149 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700150 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700151
Joe Tsai5d72cc22019-03-28 01:13:26 -0700152 // Emit a static check that enforces a minimum version of the proto package.
Joe Tsai58b42d82019-05-22 16:27:51 -0400153 g.P("const (")
154 g.P("// Verify that runtime/protoimpl is sufficiently up-to-date.")
155 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("MaxVersion"), " - ", protoimpl.Version, ")")
156 g.P("// Verify that this generated code is sufficiently up-to-date.")
157 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimpl.Version, " - ", protoimplPackage.Ident("MinVersion"), ")")
158 g.P(")")
Joe Tsai5d72cc22019-03-28 01:13:26 -0700159 g.P()
160
Damien Neil73ac8852018-09-17 15:11:24 -0700161 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
162 genImport(gen, g, f, imps.Get(i))
163 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700164 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700165 genEnum(gen, g, f, enum)
166 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700167 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700168 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700169 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700170 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700171
Joe Tsaib6405bd2018-11-15 14:44:37 -0800172 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800173
174 return g
Damien Neil7779e052018-09-07 14:14:06 -0700175}
176
Damien Neil73ac8852018-09-17 15:11:24 -0700177// walkMessages calls f on each message and all of its descendants.
178func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
179 for _, m := range messages {
180 f(m)
181 walkMessages(m.Messages, f)
182 }
183}
184
Damien Neild39efc82018-09-24 12:38:10 -0700185func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700186 impFile, ok := gen.FileByName(imp.Path())
187 if !ok {
188 return
189 }
190 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700191 // Don't generate imports or aliases for types in the same Go package.
192 return
193 }
Damien Neil40a08052018-10-29 09:07:41 -0700194 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700195 // referenced, because other code and tools depend on having the
196 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700197 if !imp.IsWeak {
198 g.Import(impFile.GoImportPath)
199 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700200 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700201 return
202 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800203
204 // Generate public imports by generating the imported file, parsing it,
205 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800206 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800207 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800208 b, err := impGen.Content()
209 if err != nil {
210 gen.Error(err)
211 return
212 }
213 fset := token.NewFileSet()
214 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
215 if err != nil {
216 gen.Error(err)
217 return
218 }
Damien Neila7cbd062019-01-06 16:29:14 -0800219 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800220 // Don't import unexported symbols.
221 r, _ := utf8.DecodeRuneInString(name)
222 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700223 return
224 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800225 // Don't import the FileDescriptor.
226 if name == impFile.GoDescriptorIdent.GoName {
227 return
228 }
Damien Neila7cbd062019-01-06 16:29:14 -0800229 // Don't import decls referencing a symbol defined in another package.
230 // i.e., don't import decls which are themselves public imports:
231 //
232 // type T = somepackage.T
233 if _, ok := expr.(*ast.SelectorExpr); ok {
234 return
235 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800236 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
237 }
238 g.P("// Symbols defined in public import of ", imp.Path())
239 g.P()
240 for _, decl := range astFile.Decls {
241 switch decl := decl.(type) {
242 case *ast.GenDecl:
243 for _, spec := range decl.Specs {
244 switch spec := spec.(type) {
245 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800246 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800247 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800248 for i, name := range spec.Names {
249 var expr ast.Expr
250 if i < len(spec.Values) {
251 expr = spec.Values[i]
252 }
253 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800254 }
255 case *ast.ImportSpec:
256 default:
257 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800258 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700259 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700260 }
Damien Neil6b541312018-10-29 09:14:14 -0700261 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700262 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700263}
264
Damien Neild39efc82018-09-24 12:38:10 -0700265func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Joe Tsai61968ce2019-04-01 12:59:24 -0700266 // Enum type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700267 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700268 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700269 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800270 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Joe Tsai61968ce2019-04-01 12:59:24 -0700271
272 // Enum value constants.
Damien Neil46abb572018-09-07 12:45:37 -0700273 g.P("const (")
274 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700275 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700276 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700277 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800278 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700279 }
280 g.P(")")
281 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800282
Joe Tsai61968ce2019-04-01 12:59:24 -0700283 // Enum value mapping (number -> name).
Joe Tsaiab61d412019-04-16 15:23:29 -0700284 if generateEnumMapVars {
285 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsaiab61d412019-04-16 15:23:29 -0700286 g.P("var ", nameMap, " = map[int32]string{")
287 generated := make(map[protoreflect.EnumNumber]bool)
288 for _, value := range enum.Values {
289 duplicate := ""
290 if _, present := generated[value.Desc.Number()]; present {
291 duplicate = "// Duplicate value: "
292 }
293 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
294 generated[value.Desc.Number()] = true
Damien Neil46abb572018-09-07 12:45:37 -0700295 }
Joe Tsaiab61d412019-04-16 15:23:29 -0700296 g.P("}")
297 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700298 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700299
Joe Tsai61968ce2019-04-01 12:59:24 -0700300 // Enum value mapping (name -> number).
Joe Tsaiab61d412019-04-16 15:23:29 -0700301 if generateEnumMapVars {
302 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsaiab61d412019-04-16 15:23:29 -0700303 g.P("var ", valueMap, " = map[string]int32{")
304 for _, value := range enum.Values {
305 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
306 }
307 g.P("}")
308 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700309 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700310
Joe Tsai61968ce2019-04-01 12:59:24 -0700311 // Enum method.
Joe Tsaidbab6c02019-05-14 15:06:03 -0700312 //
313 // NOTE: A pointer value is needed to represent presence in proto2.
314 // Since a proto2 message can reference a proto3 enum, it is useful to
315 // always generate this method (even on proto3 enums) to support that case.
316 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
317 g.P("p := new(", enum.GoIdent, ")")
318 g.P("*p = x")
319 g.P("return p")
320 g.P("}")
321 g.P()
322
Joe Tsai61968ce2019-04-01 12:59:24 -0700323 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700324 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700325 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700326 g.P("}")
327 g.P()
328
Joe Tsai61968ce2019-04-01 12:59:24 -0700329 genReflectEnum(gen, g, f, enum)
330
331 // UnmarshalJSON method.
Joe Tsai73903462018-12-14 12:22:41 -0800332 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700333 g.P("// Deprecated: Do not use.")
334 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700335 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700336 g.P("if err != nil {")
337 g.P("return err")
338 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700339 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700340 g.P("return nil")
341 g.P("}")
342 g.P()
343 }
344
Joe Tsai61968ce2019-04-01 12:59:24 -0700345 // EnumDescriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700346 if generateRawDescMethods {
347 var indexes []string
348 for i := 1; i < len(enum.Location.Path); i += 2 {
349 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
350 }
351 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
352 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
353 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
354 g.P("}")
355 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700356 }
Damien Neil46abb572018-09-07 12:45:37 -0700357
Damien Neilea7baf42018-09-28 14:23:44 -0700358 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700359}
360
Joe Tsai61968ce2019-04-01 12:59:24 -0700361// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700362//
363// Confusingly, this is <proto_package>.<go_ident>. This probably should have
364// been the full name of the proto enum type instead, but changing it at this
365// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700366func enumLegacyName(enum *protogen.Enum) string {
Joe Tsai67c1d9b2019-05-12 02:27:46 -0700367 fdesc := enum.Desc.ParentFile()
Damien Neildaa4fad2018-10-08 14:08:27 -0700368 if fdesc.Package() == "" {
369 return enum.GoIdent.GoName
370 }
Damien Neil658051b2018-09-10 12:26:21 -0700371 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
372}
373
Damien Neild39efc82018-09-24 12:38:10 -0700374func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700375 if message.Desc.IsMapEntry() {
376 return
377 }
378
Joe Tsai61968ce2019-04-01 12:59:24 -0700379 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700380 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800381 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700382 if hasComment {
383 g.P("//")
384 }
385 g.P(deprecationComment(true))
386 }
Damien Neil162c1272018-10-04 12:42:37 -0700387 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700388 g.P("type ", message.GoIdent, " struct {")
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700389 sf := f.allMessageFieldsByPtr[message]
Damien Neil658051b2018-09-10 12:26:21 -0700390 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700391 if field.Oneof != nil {
Damien Neil1fa78d82018-09-13 13:12:36 -0700392 // It would be a bit simpler to iterate over the oneofs below,
393 // but generating the field here keeps the contents of the Go
394 // struct in the same order as the contents of the source
395 // .proto file.
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700396 oneof := field.Oneof
397 if field != oneof.Fields[0] {
398 continue // already generated oneof field for first entry
Damien Neil1fa78d82018-09-13 13:12:36 -0700399 }
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700400 if g.PrintLeadingComments(oneof.Location) {
401 g.P("//")
402 }
403 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
404 for _, field := range oneof.Fields {
405 g.PrintLeadingComments(field.Location)
406 g.P("//\t*", fieldOneofType(field))
407 }
408 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
409 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
410 sf.append(oneofFieldName(oneof))
Damien Neil658051b2018-09-10 12:26:21 -0700411 continue
412 }
Damien Neilba1159f2018-10-17 12:53:18 -0700413 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700414 goType, pointer := fieldGoType(g, field)
415 if pointer {
416 goType = "*" + goType
417 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700418 tags := []string{
419 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
420 fmt.Sprintf("json:%q", fieldJSONTag(field)),
421 }
422 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700423 key := field.Message.Fields[0]
424 val := field.Message.Fields[1]
Damien Neil0bd5a382018-09-13 15:07:10 -0700425 tags = append(tags,
426 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
427 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
428 )
429 }
Damien Neil162c1272018-10-04 12:42:37 -0700430 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700431 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800432 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700433 sf.append(field.GoName)
Damien Neil658051b2018-09-10 12:26:21 -0700434 }
Damien Neil993c04d2018-09-14 15:41:11 -0700435
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700436 if generateNoUnkeyedLiteralFields {
437 g.P("XXX_NoUnkeyedLiteral", " struct{} `json:\"-\"`")
438 sf.append("XXX_NoUnkeyedLiteral")
439 }
440 if generateExportedSizeCacheFields {
441 g.P("XXX_sizecache", " ", protoimplPackage.Ident("SizeCache"), " `json:\"-\"`")
442 sf.append("XXX_sizecache")
443 } else {
444 g.P("sizeCache", " ", protoimplPackage.Ident("SizeCache"))
445 sf.append("sizeCache")
446 }
447 if generateExportedUnknownFields {
448 g.P("XXX_unrecognized", " ", protoimplPackage.Ident("UnknownFields"), " `json:\"-\"`")
449 sf.append("XXX_unrecognized")
450 } else {
451 g.P("unknownFields", " ", protoimplPackage.Ident("UnknownFields"))
452 sf.append("unknownFields")
453 }
Damien Neil993c04d2018-09-14 15:41:11 -0700454 if message.Desc.ExtensionRanges().Len() > 0 {
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700455 if generateExportedExtensionFields {
Joe Tsai6ceeaab2019-07-08 12:31:21 -0700456 g.P("XXX_InternalExtensions", " ", protoimplPackage.Ident("ExtensionFields"), " `json:\"-\"`")
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700457 sf.append("XXX_InternalExtensions")
458 } else {
Joe Tsai6ceeaab2019-07-08 12:31:21 -0700459 g.P("extensionFields", " ", protoimplPackage.Ident("ExtensionFields"))
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700460 sf.append("extensionFields")
461 }
Damien Neil993c04d2018-09-14 15:41:11 -0700462 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700463 g.P("}")
464 g.P()
465
Joe Tsai61968ce2019-04-01 12:59:24 -0700466 // Reset method.
467 g.P("func (x *", message.GoIdent, ") Reset() {")
468 g.P("*x = ", message.GoIdent, "{}")
469 g.P("}")
470 g.P()
471 // String method.
472 g.P("func (x *", message.GoIdent, ") String() string {")
473 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
474 g.P("}")
475 g.P()
476 // ProtoMessage method.
477 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
478 g.P()
479
Joe Tsaib6405bd2018-11-15 14:44:37 -0800480 genReflectMessage(gen, g, f, message)
481
Joe Tsai61968ce2019-04-01 12:59:24 -0700482 // Descriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700483 if generateRawDescMethods {
484 var indexes []string
485 for i := 1; i < len(message.Location.Path); i += 2 {
486 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
487 }
488 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
489 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
490 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
491 g.P("}")
492 g.P()
Damien Neila1c6abc2018-09-12 13:36:34 -0700493 }
Damien Neil993c04d2018-09-14 15:41:11 -0700494
Joe Tsai61968ce2019-04-01 12:59:24 -0700495 // ExtensionRangeArray method.
Damien Neil993c04d2018-09-14 15:41:11 -0700496 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700497 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700498 extRangeVar := "extRange_" + message.GoIdent.GoName
499 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
500 for i := 0; i < extranges.Len(); i++ {
501 r := extranges.Get(i)
502 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
503 }
504 g.P("}")
505 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700506 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700507 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
508 g.P("return ", extRangeVar)
509 g.P("}")
510 g.P()
511 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700512
Damien Neilea7baf42018-09-28 14:23:44 -0700513 genWellKnownType(g, "*", message.GoIdent, message.Desc)
514
Damien Neilebc699d2018-09-13 08:50:13 -0700515 // Constants and vars holding the default values of fields.
516 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800517 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700518 continue
519 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700520 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700521 def := field.Desc.Default()
522 switch field.Desc.Kind() {
523 case protoreflect.StringKind:
524 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
525 case protoreflect.BytesKind:
526 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
527 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700528 evalueDesc := field.Desc.DefaultEnumValue()
Joe Tsaid24bc722019-04-15 23:39:09 -0700529 enum := field.Enum
Damien Neila485fbd2018-10-26 13:28:37 -0700530 evalue := enum.Values[evalueDesc.Index()]
Joe Tsaid24bc722019-04-15 23:39:09 -0700531 g.P("const ", defVarName, " ", field.Enum.GoIdent, " = ", evalue.GoIdent)
Damien Neilebc699d2018-09-13 08:50:13 -0700532 case protoreflect.FloatKind, protoreflect.DoubleKind:
533 // Floating point numbers need extra handling for -Inf/Inf/NaN.
534 f := field.Desc.Default().Float()
535 goType := "float64"
536 if field.Desc.Kind() == protoreflect.FloatKind {
537 goType = "float32"
538 }
539 // funcCall returns a call to a function in the math package,
540 // possibly converting the result to float32.
541 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800542 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700543 if goType != "float64" {
544 s = goType + "(" + s + ")"
545 }
546 return s
547 }
548 switch {
549 case math.IsInf(f, -1):
550 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
551 case math.IsInf(f, 1):
552 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
553 case math.IsNaN(f):
554 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
555 default:
Damien Neil982684b2018-09-28 14:12:41 -0700556 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700557 }
558 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700559 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700560 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
561 }
562 }
563 g.P()
564
Joe Tsai61968ce2019-04-01 12:59:24 -0700565 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700566 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700567 if isFirstOneofField(field) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700568 genOneofGetter(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700569 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700570 goType, pointer := fieldGoType(g, field)
571 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800572 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700573 g.P(deprecationComment(true))
574 }
Damien Neil162c1272018-10-04 12:42:37 -0700575 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700576 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Joe Tsaid24bc722019-04-15 23:39:09 -0700577 if field.Oneof != nil {
578 g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700579 g.P("return x.", field.GoName)
580 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700581 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700582 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700583 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700584 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700585 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700586 }
587 star := ""
588 if pointer {
589 star = "*"
590 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700591 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700592 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700593 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700594 g.P("return ", defaultValue)
595 g.P("}")
596 g.P()
597 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700598
Joe Tsai09912272019-07-08 10:38:11 -0700599 // Oneof wrapper types.
Damien Neil1fa78d82018-09-13 13:12:36 -0700600 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800601 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700602 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700603}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700604
Damien Neil77f82fe2018-09-13 10:59:17 -0700605// fieldGoType returns the Go type used for a field.
606//
607// If it returns pointer=true, the struct field is a pointer to the type.
608func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700609 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700610 switch field.Desc.Kind() {
611 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700612 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700613 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700614 goType = g.QualifiedGoIdent(field.Enum.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700615 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700617 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700619 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700620 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700621 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700623 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700625 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700626 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700627 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700629 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = "[]byte"
631 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700632 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700633 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700634 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700635 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700636 switch {
637 case field.Desc.IsList():
Damien Neil77f82fe2018-09-13 10:59:17 -0700638 goType = "[]" + goType
639 pointer = false
Joe Tsaiac31a352019-05-13 14:32:56 -0700640 case field.Desc.IsMap():
641 keyType, _ := fieldGoType(g, field.Message.Fields[0])
642 valType, _ := fieldGoType(g, field.Message.Fields[1])
643 return fmt.Sprintf("map[%v]%v", keyType, valType), false
Damien Neil658051b2018-09-10 12:26:21 -0700644 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700645
Damien Neil44000a12018-10-24 12:31:16 -0700646 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaiac31a352019-05-13 14:32:56 -0700647 if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700648 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700649 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700650 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700651}
652
653func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700654 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700655 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700656 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700657 }
Joe Tsai05828db2018-11-01 13:52:16 -0700658 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700659}
660
Damien Neil77f82fe2018-09-13 10:59:17 -0700661func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
Joe Tsaiac31a352019-05-13 14:32:56 -0700662 if field.Desc.IsList() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700663 return "nil"
664 }
Joe Tsai9667c482018-12-05 15:42:52 -0800665 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700666 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700667 if field.Desc.Kind() == protoreflect.BytesKind {
668 return "append([]byte(nil), " + defVarName + "...)"
669 }
670 return defVarName
671 }
672 switch field.Desc.Kind() {
673 case protoreflect.BoolKind:
674 return "false"
675 case protoreflect.StringKind:
676 return `""`
677 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
678 return "nil"
679 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700680 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700681 default:
682 return "0"
683 }
684}
685
Damien Neil658051b2018-09-10 12:26:21 -0700686func fieldJSONTag(field *protogen.Field) string {
687 return string(field.Desc.Name()) + ",omitempty"
688}
689
Joe Tsaiafb455e2019-03-14 16:08:22 -0700690func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
691 if len(f.allExtensions) == 0 {
692 return
Damien Neil154da982018-09-19 13:21:58 -0700693 }
694
Joe Tsaid8881392019-06-06 13:01:53 -0700695 g.P("var ", extDescsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700696 for _, extension := range f.allExtensions {
Joe Tsaiafb455e2019-03-14 16:08:22 -0700697 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700698 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700699 goType, pointer := fieldGoType(g, extension)
700 if pointer {
701 goType = "*" + goType
702 }
703 g.P("ExtensionType: (", goType, ")(nil),")
704 g.P("Field: ", extension.Desc.Number(), ",")
Joe Tsai6ceeaab2019-07-08 12:31:21 -0700705 g.P("Name: ", strconv.Quote(string(extension.Desc.FullName())), ",")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700706 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
707 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
708 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700709 }
Damien Neil993c04d2018-09-14 15:41:11 -0700710 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700711
712 g.P("var (")
713 for i, extension := range f.allExtensions {
714 ed := extension.Desc
Joe Tsaiac31a352019-05-13 14:32:56 -0700715 targetName := string(ed.ContainingMessage().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700716 typeName := ed.Kind().String()
717 switch ed.Kind() {
718 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700719 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700720 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700721 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700722 }
723 fieldName := string(ed.Name())
724 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
Joe Tsaid8881392019-06-06 13:01:53 -0700725 g.P(extensionVar(f.File, extension), " = &", extDescsVarName(f), "[", i, "]")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700726 g.P()
727 }
728 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700729}
730
731// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700732func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700733 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700734 if extension.Parent != nil {
735 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700736 }
737 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800738 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700739}
740
Damien Neil55fe1c02018-09-17 15:11:24 -0700741// deprecationComment returns a standard deprecation comment if deprecated is true.
742func deprecationComment(deprecated bool) string {
743 if !deprecated {
744 return ""
745 }
746 return "// Deprecated: Do not use."
747}
748
Damien Neilea7baf42018-09-28 14:23:44 -0700749func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Joe Tsai5455ef52019-07-08 13:49:48 -0700750 if generateWKTMarkerMethods && wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700751 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700752 g.P()
753 }
754}
755
756// Names of messages and enums for which we will generate XXX_WellKnownType methods.
757var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700758 "google.protobuf.Any": true,
759 "google.protobuf.Duration": true,
760 "google.protobuf.Empty": true,
761 "google.protobuf.Struct": true,
762 "google.protobuf.Timestamp": true,
763
764 "google.protobuf.BoolValue": true,
765 "google.protobuf.BytesValue": true,
766 "google.protobuf.DoubleValue": true,
767 "google.protobuf.FloatValue": true,
768 "google.protobuf.Int32Value": true,
769 "google.protobuf.Int64Value": true,
770 "google.protobuf.ListValue": true,
771 "google.protobuf.NullValue": true,
772 "google.protobuf.StringValue": true,
773 "google.protobuf.UInt32Value": true,
774 "google.protobuf.UInt64Value": true,
775 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700776}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800777
Joe Tsai872b5002019-04-08 14:03:15 -0700778// genOneofGetter generate a Get method for a oneof.
779func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
780 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
781 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
782 g.P("if m != nil {")
783 g.P("return m.", oneofFieldName(oneof))
784 g.P("}")
785 g.P("return nil")
786 g.P("}")
787 g.P()
788}
789
Joe Tsai09912272019-07-08 10:38:11 -0700790// genOneofWrappers generates the oneof wrapper types and associates the types
791// with the parent message type.
Joe Tsai872b5002019-04-08 14:03:15 -0700792func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Joe Tsai09912272019-07-08 10:38:11 -0700793 idx := f.allMessagesByPtr[message]
794 typesVar := messageTypesVarName(f)
795
796 // Associate the wrapper types through a XXX_OneofWrappers method.
797 if generateOneofWrapperMethods {
798 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
799 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
800 g.P("return ", typesVar, "[", idx, "].OneofWrappers")
801 g.P("}")
802 g.P()
Joe Tsai872b5002019-04-08 14:03:15 -0700803 }
Joe Tsai09912272019-07-08 10:38:11 -0700804
805 // Generate the oneof wrapper types.
806 for _, oneof := range message.Oneofs {
807 genOneofTypes(gen, g, f, message, oneof)
808 }
Joe Tsai872b5002019-04-08 14:03:15 -0700809}
810
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800811// genOneofTypes generates the interface type used for a oneof field,
812// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800813func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
814 ifName := oneofInterfaceName(oneof)
815 g.P("type ", ifName, " interface {")
816 g.P(ifName, "()")
817 g.P("}")
818 g.P()
819 for _, field := range oneof.Fields {
820 name := fieldOneofType(field)
821 g.Annotate(name.GoName, field.Location)
822 g.Annotate(name.GoName+"."+field.GoName, field.Location)
823 g.P("type ", name, " struct {")
824 goType, _ := fieldGoType(g, field)
825 tags := []string{
826 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
827 }
828 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
829 g.P("}")
830 g.P()
831 }
832 for _, field := range oneof.Fields {
833 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
834 g.P()
835 }
Joe Tsai872b5002019-04-08 14:03:15 -0700836}
837
838// isFirstOneofField reports whether this is the first field in a oneof.
839func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700840 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800841}
842
843// oneofFieldName returns the name of the struct field holding the oneof value.
844//
845// This function is trivial, but pulling out the name like this makes it easier
846// to experiment with alternative oneof implementations.
847func oneofFieldName(oneof *protogen.Oneof) string {
848 return oneof.GoName
849}
850
851// oneofInterfaceName returns the name of the interface type implemented by
852// the oneof field value types.
853func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700854 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800855}
856
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800857// fieldOneofType returns the wrapper type used to represent a field in a oneof.
858func fieldOneofType(field *protogen.Field) protogen.GoIdent {
859 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700860 GoImportPath: field.Parent.GoIdent.GoImportPath,
861 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800862 }
863 // Check for collisions with nested messages or enums.
864 //
865 // This conflict resolution is incomplete: Among other things, it
866 // does not consider collisions with other oneof field types.
867 //
868 // TODO: Consider dropping this entirely. Detecting conflicts and
869 // producing an error is almost certainly better than permuting
870 // field and type names in mostly unpredictable ways.
871Loop:
872 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700873 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800874 if message.GoIdent == ident {
875 ident.GoName += "_"
876 continue Loop
877 }
878 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700879 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800880 if enum.GoIdent == ident {
881 ident.GoName += "_"
882 continue Loop
883 }
884 }
885 return ident
886 }
887}