blob: 219d79a915981e752fac3afda1aa43c894b366df [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
Joe Tsaib3d57df2019-04-17 14:07:32 -070033 // generateEnumJSONMethods specifies whether to generate the UnmarshalJSON
34 // method for proto2 enums.
35 generateEnumJSONMethods = true
36
Joe Tsaiab61d412019-04-16 15:23:29 -070037 // generateRawDescMethods specifies whether to generate EnumDescriptor and
38 // Descriptor methods for enums and messages. These methods return the
39 // GZIP'd contents of the raw file descriptor and the path from the root
40 // to the given enum or message descriptor.
41 generateRawDescMethods = true
Joe Tsai09912272019-07-08 10:38:11 -070042
43 // generateOneofWrapperMethods specifies whether to generate
44 // XXX_OneofWrappers methods on messages with oneofs.
45 generateOneofWrapperMethods = false
Joe Tsaic0e4bb22019-07-06 13:05:11 -070046
Joe Tsaib3d57df2019-04-17 14:07:32 -070047 // generateExtensionRangeMethods specifies whether to generate the
48 // ExtensionRangeArray method for messages that support extensions.
49 generateExtensionRangeMethods = true
50
Joe Tsai5455ef52019-07-08 13:49:48 -070051 // generateWKTMarkerMethods specifes whether to generate
52 // XXX_WellKnownType methods on well-known types.
53 generateWKTMarkerMethods = false
54
Joe Tsaic0e4bb22019-07-06 13:05:11 -070055 // generateNoUnkeyedLiteralFields specifies whether to generate
56 // the XXX_NoUnkeyedLiteral field.
57 generateNoUnkeyedLiteralFields = false
58
59 // generateExportedSizeCacheFields specifies whether to generate an exported
60 // XXX_sizecache field instead of an unexported sizeCache field.
61 generateExportedSizeCacheFields = false
62
63 // generateExportedUnknownFields specifies whether to generate an exported
64 // XXX_unrecognized field instead of an unexported unknownFields field.
65 generateExportedUnknownFields = false
66
67 // generateExportedExtensionFields specifies whether to generate an exported
68 // XXX_InternalExtensions field instead of an unexported extensionFields field.
69 generateExportedExtensionFields = false
Joe Tsaiab61d412019-04-16 15:23:29 -070070)
71
72const (
Joe Tsai5d72cc22019-03-28 01:13:26 -070073 syncPackage = protogen.GoImportPath("sync")
Joe Tsai4fddeba2019-03-20 18:29:32 -070074 mathPackage = protogen.GoImportPath("math")
Damien Neile89e6242019-05-13 23:55:40 -070075 protoifacePackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoiface")
76 protoimplPackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoimpl")
77 protoreflectPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoreflect")
78 protoregistryPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoregistry")
Joe Tsaid8881392019-06-06 13:01:53 -070079 prototypePackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/prototype")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080080)
Damien Neil46abb572018-09-07 12:45:37 -070081
Damien Neild39efc82018-09-24 12:38:10 -070082type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070083 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080084
Joe Tsaic0e4bb22019-07-06 13:05:11 -070085 allEnums []*protogen.Enum
86 allMessages []*protogen.Message
87 allExtensions []*protogen.Extension
88
89 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
90 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
91 allMessageFieldsByPtr map[*protogen.Message]*structFields
92}
93
94type structFields struct {
95 count int
96 unexported map[int]string
97}
98
99func (sf *structFields) append(name string) {
100 if r, _ := utf8.DecodeRuneInString(name); !unicode.IsUpper(r) {
101 if sf.unexported == nil {
102 sf.unexported = make(map[int]string)
103 }
104 sf.unexported[sf.count] = name
105 }
106 sf.count++
Damien Neilcab8dfe2018-09-06 14:51:28 -0700107}
108
Damien Neil9c420a62018-09-27 15:26:33 -0700109// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -0800110func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
111 filename := file.GeneratedFilenamePrefix + ".pb.go"
112 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -0700113 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -0700114 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -0700115 }
116
Damien Neil8012b442019-01-18 09:32:24 -0800117 // Collect all enums, messages, and extensions in "flattened ordering".
Joe Tsaid8881392019-06-06 13:01:53 -0700118 // See filetype.TypeBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -0800119 f.allEnums = append(f.allEnums, f.Enums...)
120 f.allMessages = append(f.allMessages, f.Messages...)
121 f.allExtensions = append(f.allExtensions, f.Extensions...)
122 walkMessages(f.Messages, func(m *protogen.Message) {
123 f.allEnums = append(f.allEnums, m.Enums...)
124 f.allMessages = append(f.allMessages, m.Messages...)
125 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -0700126 })
Damien Neilce36f8d2018-09-13 15:19:08 -0700127
Joe Tsai9667c482018-12-05 15:42:52 -0800128 // Derive a reverse mapping of enum and message pointers to their index
129 // in allEnums and allMessages.
130 if len(f.allEnums) > 0 {
131 f.allEnumsByPtr = make(map[*protogen.Enum]int)
132 for i, e := range f.allEnums {
133 f.allEnumsByPtr[e] = i
134 }
135 }
136 if len(f.allMessages) > 0 {
137 f.allMessagesByPtr = make(map[*protogen.Message]int)
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700138 f.allMessageFieldsByPtr = make(map[*protogen.Message]*structFields)
Joe Tsai9667c482018-12-05 15:42:52 -0800139 for i, m := range f.allMessages {
140 f.allMessagesByPtr[m] = i
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700141 f.allMessageFieldsByPtr[m] = new(structFields)
Joe Tsai9667c482018-12-05 15:42:52 -0800142 }
143 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800144
Damien Neil220c2022018-08-15 11:24:18 -0700145 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700146 if f.Proto.GetOptions().GetDeprecated() {
147 g.P("// ", f.Desc.Path(), " is a deprecated file.")
148 } else {
149 g.P("// source: ", f.Desc.Path())
150 }
Damien Neil220c2022018-08-15 11:24:18 -0700151 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -0700152 g.PrintLeadingComments(protogen.Location{
153 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -0700154 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700155 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700156 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700157 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700158 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700159
Joe Tsai5d72cc22019-03-28 01:13:26 -0700160 // Emit a static check that enforces a minimum version of the proto package.
Joe Tsai58b42d82019-05-22 16:27:51 -0400161 g.P("const (")
162 g.P("// Verify that runtime/protoimpl is sufficiently up-to-date.")
163 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("MaxVersion"), " - ", protoimpl.Version, ")")
164 g.P("// Verify that this generated code is sufficiently up-to-date.")
165 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimpl.Version, " - ", protoimplPackage.Ident("MinVersion"), ")")
166 g.P(")")
Joe Tsai5d72cc22019-03-28 01:13:26 -0700167 g.P()
168
Damien Neil73ac8852018-09-17 15:11:24 -0700169 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
170 genImport(gen, g, f, imps.Get(i))
171 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700172 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700173 genEnum(gen, g, f, enum)
174 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700175 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700176 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700177 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700178 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700179
Joe Tsaib6405bd2018-11-15 14:44:37 -0800180 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800181
182 return g
Damien Neil7779e052018-09-07 14:14:06 -0700183}
184
Damien Neil73ac8852018-09-17 15:11:24 -0700185// walkMessages calls f on each message and all of its descendants.
186func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
187 for _, m := range messages {
188 f(m)
189 walkMessages(m.Messages, f)
190 }
191}
192
Damien Neild39efc82018-09-24 12:38:10 -0700193func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700194 impFile, ok := gen.FileByName(imp.Path())
195 if !ok {
196 return
197 }
198 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700199 // Don't generate imports or aliases for types in the same Go package.
200 return
201 }
Damien Neil40a08052018-10-29 09:07:41 -0700202 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700203 // referenced, because other code and tools depend on having the
204 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700205 if !imp.IsWeak {
206 g.Import(impFile.GoImportPath)
207 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700208 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700209 return
210 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800211
212 // Generate public imports by generating the imported file, parsing it,
213 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800214 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800215 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800216 b, err := impGen.Content()
217 if err != nil {
218 gen.Error(err)
219 return
220 }
221 fset := token.NewFileSet()
222 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
223 if err != nil {
224 gen.Error(err)
225 return
226 }
Damien Neila7cbd062019-01-06 16:29:14 -0800227 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800228 // Don't import unexported symbols.
229 r, _ := utf8.DecodeRuneInString(name)
230 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700231 return
232 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800233 // Don't import the FileDescriptor.
234 if name == impFile.GoDescriptorIdent.GoName {
235 return
236 }
Damien Neila7cbd062019-01-06 16:29:14 -0800237 // Don't import decls referencing a symbol defined in another package.
238 // i.e., don't import decls which are themselves public imports:
239 //
240 // type T = somepackage.T
241 if _, ok := expr.(*ast.SelectorExpr); ok {
242 return
243 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800244 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
245 }
246 g.P("// Symbols defined in public import of ", imp.Path())
247 g.P()
248 for _, decl := range astFile.Decls {
249 switch decl := decl.(type) {
250 case *ast.GenDecl:
251 for _, spec := range decl.Specs {
252 switch spec := spec.(type) {
253 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800254 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800255 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800256 for i, name := range spec.Names {
257 var expr ast.Expr
258 if i < len(spec.Values) {
259 expr = spec.Values[i]
260 }
261 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800262 }
263 case *ast.ImportSpec:
264 default:
265 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800266 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700267 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700268 }
Damien Neil6b541312018-10-29 09:14:14 -0700269 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700270 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700271}
272
Damien Neild39efc82018-09-24 12:38:10 -0700273func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Joe Tsai61968ce2019-04-01 12:59:24 -0700274 // Enum type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700275 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700276 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700277 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800278 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Joe Tsai61968ce2019-04-01 12:59:24 -0700279
280 // Enum value constants.
Damien Neil46abb572018-09-07 12:45:37 -0700281 g.P("const (")
282 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700283 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700284 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700285 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800286 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700287 }
288 g.P(")")
289 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800290
Joe Tsai61968ce2019-04-01 12:59:24 -0700291 // Enum value mapping (number -> name).
Joe Tsaiab61d412019-04-16 15:23:29 -0700292 if generateEnumMapVars {
293 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsaiab61d412019-04-16 15:23:29 -0700294 g.P("var ", nameMap, " = map[int32]string{")
295 generated := make(map[protoreflect.EnumNumber]bool)
296 for _, value := range enum.Values {
297 duplicate := ""
298 if _, present := generated[value.Desc.Number()]; present {
299 duplicate = "// Duplicate value: "
300 }
301 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
302 generated[value.Desc.Number()] = true
Damien Neil46abb572018-09-07 12:45:37 -0700303 }
Joe Tsaiab61d412019-04-16 15:23:29 -0700304 g.P("}")
305 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700306 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700307
Joe Tsai61968ce2019-04-01 12:59:24 -0700308 // Enum value mapping (name -> number).
Joe Tsaiab61d412019-04-16 15:23:29 -0700309 if generateEnumMapVars {
310 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsaiab61d412019-04-16 15:23:29 -0700311 g.P("var ", valueMap, " = map[string]int32{")
312 for _, value := range enum.Values {
313 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
314 }
315 g.P("}")
316 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700317 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700318
Joe Tsai61968ce2019-04-01 12:59:24 -0700319 // Enum method.
Joe Tsaidbab6c02019-05-14 15:06:03 -0700320 //
321 // NOTE: A pointer value is needed to represent presence in proto2.
322 // Since a proto2 message can reference a proto3 enum, it is useful to
323 // always generate this method (even on proto3 enums) to support that case.
324 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
325 g.P("p := new(", enum.GoIdent, ")")
326 g.P("*p = x")
327 g.P("return p")
328 g.P("}")
329 g.P()
330
Joe Tsai61968ce2019-04-01 12:59:24 -0700331 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700332 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700333 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700334 g.P("}")
335 g.P()
336
Joe Tsai61968ce2019-04-01 12:59:24 -0700337 genReflectEnum(gen, g, f, enum)
338
339 // UnmarshalJSON method.
Joe Tsaib3d57df2019-04-17 14:07:32 -0700340 if generateEnumJSONMethods && enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700341 g.P("// Deprecated: Do not use.")
342 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700343 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700344 g.P("if err != nil {")
345 g.P("return err")
346 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700347 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700348 g.P("return nil")
349 g.P("}")
350 g.P()
351 }
352
Joe Tsai61968ce2019-04-01 12:59:24 -0700353 // EnumDescriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700354 if generateRawDescMethods {
355 var indexes []string
356 for i := 1; i < len(enum.Location.Path); i += 2 {
357 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
358 }
359 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
360 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
361 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
362 g.P("}")
363 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700364 }
Damien Neil46abb572018-09-07 12:45:37 -0700365
Damien Neilea7baf42018-09-28 14:23:44 -0700366 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700367}
368
Joe Tsai61968ce2019-04-01 12:59:24 -0700369// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700370//
371// Confusingly, this is <proto_package>.<go_ident>. This probably should have
372// been the full name of the proto enum type instead, but changing it at this
373// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700374func enumLegacyName(enum *protogen.Enum) string {
Joe Tsai67c1d9b2019-05-12 02:27:46 -0700375 fdesc := enum.Desc.ParentFile()
Damien Neildaa4fad2018-10-08 14:08:27 -0700376 if fdesc.Package() == "" {
377 return enum.GoIdent.GoName
378 }
Damien Neil658051b2018-09-10 12:26:21 -0700379 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
380}
381
Damien Neild39efc82018-09-24 12:38:10 -0700382func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700383 if message.Desc.IsMapEntry() {
384 return
385 }
386
Joe Tsai61968ce2019-04-01 12:59:24 -0700387 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700388 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800389 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700390 if hasComment {
391 g.P("//")
392 }
393 g.P(deprecationComment(true))
394 }
Damien Neil162c1272018-10-04 12:42:37 -0700395 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700396 g.P("type ", message.GoIdent, " struct {")
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700397 sf := f.allMessageFieldsByPtr[message]
Damien Neil658051b2018-09-10 12:26:21 -0700398 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700399 if field.Oneof != nil {
Damien Neil1fa78d82018-09-13 13:12:36 -0700400 // It would be a bit simpler to iterate over the oneofs below,
401 // but generating the field here keeps the contents of the Go
402 // struct in the same order as the contents of the source
403 // .proto file.
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700404 oneof := field.Oneof
405 if field != oneof.Fields[0] {
406 continue // already generated oneof field for first entry
Damien Neil1fa78d82018-09-13 13:12:36 -0700407 }
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700408 if g.PrintLeadingComments(oneof.Location) {
409 g.P("//")
410 }
411 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
412 for _, field := range oneof.Fields {
413 g.PrintLeadingComments(field.Location)
414 g.P("//\t*", fieldOneofType(field))
415 }
416 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
417 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
418 sf.append(oneofFieldName(oneof))
Damien Neil658051b2018-09-10 12:26:21 -0700419 continue
420 }
Damien Neilba1159f2018-10-17 12:53:18 -0700421 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700422 goType, pointer := fieldGoType(g, field)
423 if pointer {
424 goType = "*" + goType
425 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700426 tags := []string{
427 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
428 fmt.Sprintf("json:%q", fieldJSONTag(field)),
429 }
430 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700431 key := field.Message.Fields[0]
432 val := field.Message.Fields[1]
Damien Neil0bd5a382018-09-13 15:07:10 -0700433 tags = append(tags,
434 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
435 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
436 )
437 }
Damien Neil162c1272018-10-04 12:42:37 -0700438 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700439 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800440 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700441 sf.append(field.GoName)
Damien Neil658051b2018-09-10 12:26:21 -0700442 }
Damien Neil993c04d2018-09-14 15:41:11 -0700443
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700444 if generateNoUnkeyedLiteralFields {
445 g.P("XXX_NoUnkeyedLiteral", " struct{} `json:\"-\"`")
446 sf.append("XXX_NoUnkeyedLiteral")
447 }
448 if generateExportedSizeCacheFields {
449 g.P("XXX_sizecache", " ", protoimplPackage.Ident("SizeCache"), " `json:\"-\"`")
450 sf.append("XXX_sizecache")
451 } else {
452 g.P("sizeCache", " ", protoimplPackage.Ident("SizeCache"))
453 sf.append("sizeCache")
454 }
455 if generateExportedUnknownFields {
456 g.P("XXX_unrecognized", " ", protoimplPackage.Ident("UnknownFields"), " `json:\"-\"`")
457 sf.append("XXX_unrecognized")
458 } else {
459 g.P("unknownFields", " ", protoimplPackage.Ident("UnknownFields"))
460 sf.append("unknownFields")
461 }
Damien Neil993c04d2018-09-14 15:41:11 -0700462 if message.Desc.ExtensionRanges().Len() > 0 {
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700463 if generateExportedExtensionFields {
Joe Tsai6ceeaab2019-07-08 12:31:21 -0700464 g.P("XXX_InternalExtensions", " ", protoimplPackage.Ident("ExtensionFields"), " `json:\"-\"`")
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700465 sf.append("XXX_InternalExtensions")
466 } else {
Joe Tsai6ceeaab2019-07-08 12:31:21 -0700467 g.P("extensionFields", " ", protoimplPackage.Ident("ExtensionFields"))
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700468 sf.append("extensionFields")
469 }
Damien Neil993c04d2018-09-14 15:41:11 -0700470 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700471 g.P("}")
472 g.P()
473
Joe Tsai61968ce2019-04-01 12:59:24 -0700474 // Reset method.
475 g.P("func (x *", message.GoIdent, ") Reset() {")
476 g.P("*x = ", message.GoIdent, "{}")
477 g.P("}")
478 g.P()
479 // String method.
480 g.P("func (x *", message.GoIdent, ") String() string {")
481 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
482 g.P("}")
483 g.P()
484 // ProtoMessage method.
485 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
486 g.P()
487
Joe Tsaib6405bd2018-11-15 14:44:37 -0800488 genReflectMessage(gen, g, f, message)
489
Joe Tsai61968ce2019-04-01 12:59:24 -0700490 // Descriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700491 if generateRawDescMethods {
492 var indexes []string
493 for i := 1; i < len(message.Location.Path); i += 2 {
494 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
495 }
496 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
497 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
498 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
499 g.P("}")
500 g.P()
Damien Neila1c6abc2018-09-12 13:36:34 -0700501 }
Damien Neil993c04d2018-09-14 15:41:11 -0700502
Joe Tsai61968ce2019-04-01 12:59:24 -0700503 // ExtensionRangeArray method.
Joe Tsaib3d57df2019-04-17 14:07:32 -0700504 if generateExtensionRangeMethods {
505 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
506 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
507 extRangeVar := "extRange_" + message.GoIdent.GoName
508 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
509 for i := 0; i < extranges.Len(); i++ {
510 r := extranges.Get(i)
511 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
512 }
513 g.P("}")
514 g.P()
515 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
516 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
517 g.P("return ", extRangeVar)
518 g.P("}")
519 g.P()
Damien Neil993c04d2018-09-14 15:41:11 -0700520 }
Damien Neil993c04d2018-09-14 15:41:11 -0700521 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700522
Damien Neilea7baf42018-09-28 14:23:44 -0700523 genWellKnownType(g, "*", message.GoIdent, message.Desc)
524
Damien Neilebc699d2018-09-13 08:50:13 -0700525 // Constants and vars holding the default values of fields.
526 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800527 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700528 continue
529 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700530 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700531 def := field.Desc.Default()
532 switch field.Desc.Kind() {
533 case protoreflect.StringKind:
534 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
535 case protoreflect.BytesKind:
536 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
537 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700538 evalueDesc := field.Desc.DefaultEnumValue()
Joe Tsaid24bc722019-04-15 23:39:09 -0700539 enum := field.Enum
Damien Neila485fbd2018-10-26 13:28:37 -0700540 evalue := enum.Values[evalueDesc.Index()]
Joe Tsaid24bc722019-04-15 23:39:09 -0700541 g.P("const ", defVarName, " ", field.Enum.GoIdent, " = ", evalue.GoIdent)
Damien Neilebc699d2018-09-13 08:50:13 -0700542 case protoreflect.FloatKind, protoreflect.DoubleKind:
543 // Floating point numbers need extra handling for -Inf/Inf/NaN.
544 f := field.Desc.Default().Float()
545 goType := "float64"
546 if field.Desc.Kind() == protoreflect.FloatKind {
547 goType = "float32"
548 }
549 // funcCall returns a call to a function in the math package,
550 // possibly converting the result to float32.
551 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800552 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700553 if goType != "float64" {
554 s = goType + "(" + s + ")"
555 }
556 return s
557 }
558 switch {
559 case math.IsInf(f, -1):
560 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
561 case math.IsInf(f, 1):
562 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
563 case math.IsNaN(f):
564 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
565 default:
Damien Neil982684b2018-09-28 14:12:41 -0700566 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700567 }
568 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700569 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700570 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
571 }
572 }
573 g.P()
574
Joe Tsai61968ce2019-04-01 12:59:24 -0700575 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700576 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700577 if isFirstOneofField(field) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700578 genOneofGetter(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700579 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700580 goType, pointer := fieldGoType(g, field)
581 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800582 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700583 g.P(deprecationComment(true))
584 }
Damien Neil162c1272018-10-04 12:42:37 -0700585 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700586 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Joe Tsaid24bc722019-04-15 23:39:09 -0700587 if field.Oneof != nil {
588 g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700589 g.P("return x.", field.GoName)
590 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700591 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700592 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700593 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700594 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700595 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700596 }
597 star := ""
598 if pointer {
599 star = "*"
600 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700601 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700602 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700603 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700604 g.P("return ", defaultValue)
605 g.P("}")
606 g.P()
607 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700608
Joe Tsai09912272019-07-08 10:38:11 -0700609 // Oneof wrapper types.
Damien Neil1fa78d82018-09-13 13:12:36 -0700610 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800611 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700612 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700613}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700614
Damien Neil77f82fe2018-09-13 10:59:17 -0700615// fieldGoType returns the Go type used for a field.
616//
617// If it returns pointer=true, the struct field is a pointer to the type.
618func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700619 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700620 switch field.Desc.Kind() {
621 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700623 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700624 goType = g.QualifiedGoIdent(field.Enum.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700625 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700626 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700627 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700629 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700631 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700632 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700633 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700634 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700635 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700636 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700637 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700638 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700639 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700640 goType = "[]byte"
641 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700642 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700643 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700644 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700645 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700646 switch {
647 case field.Desc.IsList():
Damien Neil77f82fe2018-09-13 10:59:17 -0700648 goType = "[]" + goType
649 pointer = false
Joe Tsaiac31a352019-05-13 14:32:56 -0700650 case field.Desc.IsMap():
651 keyType, _ := fieldGoType(g, field.Message.Fields[0])
652 valType, _ := fieldGoType(g, field.Message.Fields[1])
653 return fmt.Sprintf("map[%v]%v", keyType, valType), false
Damien Neil658051b2018-09-10 12:26:21 -0700654 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700655
Damien Neil44000a12018-10-24 12:31:16 -0700656 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaiac31a352019-05-13 14:32:56 -0700657 if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700658 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700659 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700660 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700661}
662
663func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700664 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700665 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700666 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700667 }
Joe Tsai05828db2018-11-01 13:52:16 -0700668 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700669}
670
Damien Neil77f82fe2018-09-13 10:59:17 -0700671func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
Joe Tsaiac31a352019-05-13 14:32:56 -0700672 if field.Desc.IsList() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700673 return "nil"
674 }
Joe Tsai9667c482018-12-05 15:42:52 -0800675 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700676 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700677 if field.Desc.Kind() == protoreflect.BytesKind {
678 return "append([]byte(nil), " + defVarName + "...)"
679 }
680 return defVarName
681 }
682 switch field.Desc.Kind() {
683 case protoreflect.BoolKind:
684 return "false"
685 case protoreflect.StringKind:
686 return `""`
687 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
688 return "nil"
689 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700690 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700691 default:
692 return "0"
693 }
694}
695
Damien Neil658051b2018-09-10 12:26:21 -0700696func fieldJSONTag(field *protogen.Field) string {
697 return string(field.Desc.Name()) + ",omitempty"
698}
699
Joe Tsaiafb455e2019-03-14 16:08:22 -0700700func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
701 if len(f.allExtensions) == 0 {
702 return
Damien Neil154da982018-09-19 13:21:58 -0700703 }
704
Joe Tsaid8881392019-06-06 13:01:53 -0700705 g.P("var ", extDescsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700706 for _, extension := range f.allExtensions {
Joe Tsaiafb455e2019-03-14 16:08:22 -0700707 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700708 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700709 goType, pointer := fieldGoType(g, extension)
710 if pointer {
711 goType = "*" + goType
712 }
713 g.P("ExtensionType: (", goType, ")(nil),")
714 g.P("Field: ", extension.Desc.Number(), ",")
Joe Tsai6ceeaab2019-07-08 12:31:21 -0700715 g.P("Name: ", strconv.Quote(string(extension.Desc.FullName())), ",")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700716 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
717 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
718 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700719 }
Damien Neil993c04d2018-09-14 15:41:11 -0700720 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700721
722 g.P("var (")
723 for i, extension := range f.allExtensions {
724 ed := extension.Desc
Joe Tsaiac31a352019-05-13 14:32:56 -0700725 targetName := string(ed.ContainingMessage().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700726 typeName := ed.Kind().String()
727 switch ed.Kind() {
728 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700729 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700730 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700731 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700732 }
733 fieldName := string(ed.Name())
734 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
Joe Tsaid8881392019-06-06 13:01:53 -0700735 g.P(extensionVar(f.File, extension), " = &", extDescsVarName(f), "[", i, "]")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700736 g.P()
737 }
738 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700739}
740
741// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700742func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700743 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700744 if extension.Parent != nil {
745 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700746 }
747 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800748 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700749}
750
Damien Neil55fe1c02018-09-17 15:11:24 -0700751// deprecationComment returns a standard deprecation comment if deprecated is true.
752func deprecationComment(deprecated bool) string {
753 if !deprecated {
754 return ""
755 }
756 return "// Deprecated: Do not use."
757}
758
Damien Neilea7baf42018-09-28 14:23:44 -0700759func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Joe Tsai5455ef52019-07-08 13:49:48 -0700760 if generateWKTMarkerMethods && wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700761 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700762 g.P()
763 }
764}
765
766// Names of messages and enums for which we will generate XXX_WellKnownType methods.
767var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700768 "google.protobuf.Any": true,
769 "google.protobuf.Duration": true,
770 "google.protobuf.Empty": true,
771 "google.protobuf.Struct": true,
772 "google.protobuf.Timestamp": true,
773
774 "google.protobuf.BoolValue": true,
775 "google.protobuf.BytesValue": true,
776 "google.protobuf.DoubleValue": true,
777 "google.protobuf.FloatValue": true,
778 "google.protobuf.Int32Value": true,
779 "google.protobuf.Int64Value": true,
780 "google.protobuf.ListValue": true,
781 "google.protobuf.NullValue": true,
782 "google.protobuf.StringValue": true,
783 "google.protobuf.UInt32Value": true,
784 "google.protobuf.UInt64Value": true,
785 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700786}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800787
Joe Tsai872b5002019-04-08 14:03:15 -0700788// genOneofGetter generate a Get method for a oneof.
789func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
790 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
791 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
792 g.P("if m != nil {")
793 g.P("return m.", oneofFieldName(oneof))
794 g.P("}")
795 g.P("return nil")
796 g.P("}")
797 g.P()
798}
799
Joe Tsai09912272019-07-08 10:38:11 -0700800// genOneofWrappers generates the oneof wrapper types and associates the types
801// with the parent message type.
Joe Tsai872b5002019-04-08 14:03:15 -0700802func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Joe Tsai09912272019-07-08 10:38:11 -0700803 idx := f.allMessagesByPtr[message]
804 typesVar := messageTypesVarName(f)
805
806 // Associate the wrapper types through a XXX_OneofWrappers method.
807 if generateOneofWrapperMethods {
808 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
809 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
810 g.P("return ", typesVar, "[", idx, "].OneofWrappers")
811 g.P("}")
812 g.P()
Joe Tsai872b5002019-04-08 14:03:15 -0700813 }
Joe Tsai09912272019-07-08 10:38:11 -0700814
815 // Generate the oneof wrapper types.
816 for _, oneof := range message.Oneofs {
817 genOneofTypes(gen, g, f, message, oneof)
818 }
Joe Tsai872b5002019-04-08 14:03:15 -0700819}
820
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800821// genOneofTypes generates the interface type used for a oneof field,
822// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800823func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
824 ifName := oneofInterfaceName(oneof)
825 g.P("type ", ifName, " interface {")
826 g.P(ifName, "()")
827 g.P("}")
828 g.P()
829 for _, field := range oneof.Fields {
830 name := fieldOneofType(field)
831 g.Annotate(name.GoName, field.Location)
832 g.Annotate(name.GoName+"."+field.GoName, field.Location)
833 g.P("type ", name, " struct {")
834 goType, _ := fieldGoType(g, field)
835 tags := []string{
836 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
837 }
838 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
839 g.P("}")
840 g.P()
841 }
842 for _, field := range oneof.Fields {
843 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
844 g.P()
845 }
Joe Tsai872b5002019-04-08 14:03:15 -0700846}
847
848// isFirstOneofField reports whether this is the first field in a oneof.
849func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700850 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800851}
852
853// oneofFieldName returns the name of the struct field holding the oneof value.
854//
855// This function is trivial, but pulling out the name like this makes it easier
856// to experiment with alternative oneof implementations.
857func oneofFieldName(oneof *protogen.Oneof) string {
858 return oneof.GoName
859}
860
861// oneofInterfaceName returns the name of the interface type implemented by
862// the oneof field value types.
863func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700864 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800865}
866
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800867// fieldOneofType returns the wrapper type used to represent a field in a oneof.
868func fieldOneofType(field *protogen.Field) protogen.GoIdent {
869 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700870 GoImportPath: field.Parent.GoIdent.GoImportPath,
871 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800872 }
873 // Check for collisions with nested messages or enums.
874 //
875 // This conflict resolution is incomplete: Among other things, it
876 // does not consider collisions with other oneof field types.
877 //
878 // TODO: Consider dropping this entirely. Detecting conflicts and
879 // producing an error is almost certainly better than permuting
880 // field and type names in mostly unpredictable ways.
881Loop:
882 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700883 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800884 if message.GoIdent == ident {
885 ident.GoName += "_"
886 continue Loop
887 }
888 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700889 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800890 if enum.GoIdent == ident {
891 ident.GoName += "_"
892 continue Loop
893 }
894 }
895 return ident
896 }
897}