blob: 37bdc3d87b3adeff47ff7ba701520a5e4a3cd1fe [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 Tsaie1f8d502018-11-26 18:55:29 -080023
Damien Neile89e6242019-05-13 23:55:40 -070024 descriptorpb "google.golang.org/protobuf/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070025)
26
Joe Tsai5d72cc22019-03-28 01:13:26 -070027// minimumVersion is minimum version of the v2 proto package that is required.
28// This is incremented every time the generated code relies on some property
29// in the proto package that was introduced in a later version.
30const minimumVersion = 0
31
Joe Tsaic1c17aa2018-11-16 11:14:14 -080032const (
Joe Tsaiab61d412019-04-16 15:23:29 -070033 // generateEnumMapVars specifies whether to generate enum maps,
34 // which provide a bi-directional mapping between enum numbers and names.
35 generateEnumMapVars = true
36
37 // 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
42)
43
44const (
Joe Tsai5d72cc22019-03-28 01:13:26 -070045 syncPackage = protogen.GoImportPath("sync")
Joe Tsai4fddeba2019-03-20 18:29:32 -070046 mathPackage = protogen.GoImportPath("math")
Damien Neile89e6242019-05-13 23:55:40 -070047 protoifacePackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoiface")
48 protoimplPackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoimpl")
49 protoreflectPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoreflect")
50 protoregistryPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoregistry")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080051)
Damien Neil46abb572018-09-07 12:45:37 -070052
Damien Neild39efc82018-09-24 12:38:10 -070053type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070054 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080055
Joe Tsai9667c482018-12-05 15:42:52 -080056 allEnums []*protogen.Enum
57 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
58 allMessages []*protogen.Message
59 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
60 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070061}
62
Damien Neil9c420a62018-09-27 15:26:33 -070063// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080064func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
65 filename := file.GeneratedFilenamePrefix + ".pb.go"
66 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070067 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070068 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070069 }
70
Damien Neil8012b442019-01-18 09:32:24 -080071 // Collect all enums, messages, and extensions in "flattened ordering".
72 // See fileinit.FileBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080073 f.allEnums = append(f.allEnums, f.Enums...)
74 f.allMessages = append(f.allMessages, f.Messages...)
75 f.allExtensions = append(f.allExtensions, f.Extensions...)
76 walkMessages(f.Messages, func(m *protogen.Message) {
77 f.allEnums = append(f.allEnums, m.Enums...)
78 f.allMessages = append(f.allMessages, m.Messages...)
79 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070080 })
Damien Neilce36f8d2018-09-13 15:19:08 -070081
Joe Tsai9667c482018-12-05 15:42:52 -080082 // Derive a reverse mapping of enum and message pointers to their index
83 // in allEnums and allMessages.
84 if len(f.allEnums) > 0 {
85 f.allEnumsByPtr = make(map[*protogen.Enum]int)
86 for i, e := range f.allEnums {
87 f.allEnumsByPtr[e] = i
88 }
89 }
90 if len(f.allMessages) > 0 {
91 f.allMessagesByPtr = make(map[*protogen.Message]int)
92 for i, m := range f.allMessages {
93 f.allMessagesByPtr[m] = i
94 }
95 }
Joe Tsaib6405bd2018-11-15 14:44:37 -080096
Damien Neil220c2022018-08-15 11:24:18 -070097 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070098 if f.Proto.GetOptions().GetDeprecated() {
99 g.P("// ", f.Desc.Path(), " is a deprecated file.")
100 } else {
101 g.P("// source: ", f.Desc.Path())
102 }
Damien Neil220c2022018-08-15 11:24:18 -0700103 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -0700104 g.PrintLeadingComments(protogen.Location{
105 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -0700106 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700107 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700108 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700109 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700110 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700111
Joe Tsai5d72cc22019-03-28 01:13:26 -0700112 // Emit a static check that enforces a minimum version of the proto package.
113 g.P("const _ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("Version"), " - ", minimumVersion, ")")
114 g.P()
115
Damien Neil73ac8852018-09-17 15:11:24 -0700116 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
117 genImport(gen, g, f, imps.Get(i))
118 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700119 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700120 genEnum(gen, g, f, enum)
121 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700122 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700123 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700124 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700125 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700126
Joe Tsaib6405bd2018-11-15 14:44:37 -0800127 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800128
129 return g
Damien Neil7779e052018-09-07 14:14:06 -0700130}
131
Damien Neil73ac8852018-09-17 15:11:24 -0700132// walkMessages calls f on each message and all of its descendants.
133func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
134 for _, m := range messages {
135 f(m)
136 walkMessages(m.Messages, f)
137 }
138}
139
Damien Neild39efc82018-09-24 12:38:10 -0700140func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700141 impFile, ok := gen.FileByName(imp.Path())
142 if !ok {
143 return
144 }
145 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700146 // Don't generate imports or aliases for types in the same Go package.
147 return
148 }
Damien Neil40a08052018-10-29 09:07:41 -0700149 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700150 // referenced, because other code and tools depend on having the
151 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700152 if !imp.IsWeak {
153 g.Import(impFile.GoImportPath)
154 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700155 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700156 return
157 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800158
159 // Generate public imports by generating the imported file, parsing it,
160 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800161 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800162 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800163 b, err := impGen.Content()
164 if err != nil {
165 gen.Error(err)
166 return
167 }
168 fset := token.NewFileSet()
169 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
170 if err != nil {
171 gen.Error(err)
172 return
173 }
Damien Neila7cbd062019-01-06 16:29:14 -0800174 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800175 // Don't import unexported symbols.
176 r, _ := utf8.DecodeRuneInString(name)
177 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700178 return
179 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800180 // Don't import the FileDescriptor.
181 if name == impFile.GoDescriptorIdent.GoName {
182 return
183 }
Damien Neila7cbd062019-01-06 16:29:14 -0800184 // Don't import decls referencing a symbol defined in another package.
185 // i.e., don't import decls which are themselves public imports:
186 //
187 // type T = somepackage.T
188 if _, ok := expr.(*ast.SelectorExpr); ok {
189 return
190 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800191 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
192 }
193 g.P("// Symbols defined in public import of ", imp.Path())
194 g.P()
195 for _, decl := range astFile.Decls {
196 switch decl := decl.(type) {
197 case *ast.GenDecl:
198 for _, spec := range decl.Specs {
199 switch spec := spec.(type) {
200 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800201 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800202 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800203 for i, name := range spec.Names {
204 var expr ast.Expr
205 if i < len(spec.Values) {
206 expr = spec.Values[i]
207 }
208 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800209 }
210 case *ast.ImportSpec:
211 default:
212 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800213 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700214 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700215 }
Damien Neil6b541312018-10-29 09:14:14 -0700216 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700217 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700218}
219
Damien Neild39efc82018-09-24 12:38:10 -0700220func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Joe Tsai61968ce2019-04-01 12:59:24 -0700221 // Enum type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700222 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700223 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700224 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800225 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Joe Tsai61968ce2019-04-01 12:59:24 -0700226
227 // Enum value constants.
Damien Neil46abb572018-09-07 12:45:37 -0700228 g.P("const (")
229 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700230 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700231 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700232 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800233 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700234 }
235 g.P(")")
236 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800237
Joe Tsai61968ce2019-04-01 12:59:24 -0700238 // Enum value mapping (number -> name).
Joe Tsaiab61d412019-04-16 15:23:29 -0700239 if generateEnumMapVars {
240 nameMap := enum.GoIdent.GoName + "_name"
241 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
242 g.P("var ", nameMap, " = map[int32]string{")
243 generated := make(map[protoreflect.EnumNumber]bool)
244 for _, value := range enum.Values {
245 duplicate := ""
246 if _, present := generated[value.Desc.Number()]; present {
247 duplicate = "// Duplicate value: "
248 }
249 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
250 generated[value.Desc.Number()] = true
Damien Neil46abb572018-09-07 12:45:37 -0700251 }
Joe Tsaiab61d412019-04-16 15:23:29 -0700252 g.P("}")
253 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700254 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700255
Joe Tsai61968ce2019-04-01 12:59:24 -0700256 // Enum value mapping (name -> number).
Joe Tsaiab61d412019-04-16 15:23:29 -0700257 if generateEnumMapVars {
258 valueMap := enum.GoIdent.GoName + "_value"
259 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
260 g.P("var ", valueMap, " = map[string]int32{")
261 for _, value := range enum.Values {
262 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
263 }
264 g.P("}")
265 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700266 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700267
Joe Tsai61968ce2019-04-01 12:59:24 -0700268 // Enum method.
Damien Neil46abb572018-09-07 12:45:37 -0700269 if enum.Desc.Syntax() != protoreflect.Proto3 {
270 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
Joe Tsai09b5b462019-04-10 15:29:01 -0700271 g.P("p := new(", enum.GoIdent, ")")
272 g.P("*p = x")
273 g.P("return p")
Damien Neil46abb572018-09-07 12:45:37 -0700274 g.P("}")
275 g.P()
276 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700277 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700278 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700279 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700280 g.P("}")
281 g.P()
282
Joe Tsai61968ce2019-04-01 12:59:24 -0700283 genReflectEnum(gen, g, f, enum)
284
285 // UnmarshalJSON method.
Joe Tsai73903462018-12-14 12:22:41 -0800286 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700287 g.P("// Deprecated: Do not use.")
288 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700289 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700290 g.P("if err != nil {")
291 g.P("return err")
292 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700293 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700294 g.P("return nil")
295 g.P("}")
296 g.P()
297 }
298
Joe Tsai61968ce2019-04-01 12:59:24 -0700299 // EnumDescriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700300 if generateRawDescMethods {
301 var indexes []string
302 for i := 1; i < len(enum.Location.Path); i += 2 {
303 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
304 }
305 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
306 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
307 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
308 g.P("}")
309 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700310 }
Damien Neil46abb572018-09-07 12:45:37 -0700311
Damien Neilea7baf42018-09-28 14:23:44 -0700312 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700313}
314
Joe Tsai61968ce2019-04-01 12:59:24 -0700315// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700316//
317// Confusingly, this is <proto_package>.<go_ident>. This probably should have
318// been the full name of the proto enum type instead, but changing it at this
319// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700320func enumLegacyName(enum *protogen.Enum) string {
Joe Tsai67c1d9b2019-05-12 02:27:46 -0700321 fdesc := enum.Desc.ParentFile()
Damien Neildaa4fad2018-10-08 14:08:27 -0700322 if fdesc.Package() == "" {
323 return enum.GoIdent.GoName
324 }
Damien Neil658051b2018-09-10 12:26:21 -0700325 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
326}
327
Damien Neild39efc82018-09-24 12:38:10 -0700328func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700329 if message.Desc.IsMapEntry() {
330 return
331 }
332
Joe Tsai61968ce2019-04-01 12:59:24 -0700333 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700334 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800335 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700336 if hasComment {
337 g.P("//")
338 }
339 g.P(deprecationComment(true))
340 }
Damien Neil162c1272018-10-04 12:42:37 -0700341 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700342 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700343 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700344 if field.Oneof != nil {
Damien Neil1fa78d82018-09-13 13:12:36 -0700345 // It would be a bit simpler to iterate over the oneofs below,
346 // but generating the field here keeps the contents of the Go
347 // struct in the same order as the contents of the source
348 // .proto file.
Joe Tsaid24bc722019-04-15 23:39:09 -0700349 if field == field.Oneof.Fields[0] {
350 genOneofField(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700351 }
Damien Neil658051b2018-09-10 12:26:21 -0700352 continue
353 }
Damien Neilba1159f2018-10-17 12:53:18 -0700354 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700355 goType, pointer := fieldGoType(g, field)
356 if pointer {
357 goType = "*" + goType
358 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700359 tags := []string{
360 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
361 fmt.Sprintf("json:%q", fieldJSONTag(field)),
362 }
363 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700364 key := field.Message.Fields[0]
365 val := field.Message.Fields[1]
Damien Neil0bd5a382018-09-13 15:07:10 -0700366 tags = append(tags,
367 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
368 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
369 )
370 }
Damien Neil162c1272018-10-04 12:42:37 -0700371 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700372 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800373 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700374 }
375 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700376
377 if message.Desc.ExtensionRanges().Len() > 0 {
378 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800379 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700380 tags = append(tags, `protobuf_messageset:"1"`)
381 }
382 tags = append(tags, `json:"-"`)
Joe Tsai5e71dc92019-04-16 13:22:20 -0700383 g.P("XXX_InternalExtensions ", protoimplPackage.Ident("ExtensionFields"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700384 }
Joe Tsai5e71dc92019-04-16 13:22:20 -0700385 g.P("XXX_unrecognized ", protoimplPackage.Ident("UnknownFields"), " `json:\"-\"`")
386 g.P("XXX_sizecache ", protoimplPackage.Ident("SizeCache"), " `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700387 g.P("}")
388 g.P()
389
Joe Tsai61968ce2019-04-01 12:59:24 -0700390 // Reset method.
391 g.P("func (x *", message.GoIdent, ") Reset() {")
392 g.P("*x = ", message.GoIdent, "{}")
393 g.P("}")
394 g.P()
395 // String method.
396 g.P("func (x *", message.GoIdent, ") String() string {")
397 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
398 g.P("}")
399 g.P()
400 // ProtoMessage method.
401 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
402 g.P()
403
Joe Tsaib6405bd2018-11-15 14:44:37 -0800404 genReflectMessage(gen, g, f, message)
405
Joe Tsai61968ce2019-04-01 12:59:24 -0700406 // Descriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700407 if generateRawDescMethods {
408 var indexes []string
409 for i := 1; i < len(message.Location.Path); i += 2 {
410 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
411 }
412 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
413 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
414 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
415 g.P("}")
416 g.P()
Damien Neila1c6abc2018-09-12 13:36:34 -0700417 }
Damien Neil993c04d2018-09-14 15:41:11 -0700418
Joe Tsai61968ce2019-04-01 12:59:24 -0700419 // ExtensionRangeArray method.
Damien Neil993c04d2018-09-14 15:41:11 -0700420 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700421 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700422 extRangeVar := "extRange_" + message.GoIdent.GoName
423 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
424 for i := 0; i < extranges.Len(); i++ {
425 r := extranges.Get(i)
426 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
427 }
428 g.P("}")
429 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700430 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700431 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
432 g.P("return ", extRangeVar)
433 g.P("}")
434 g.P()
435 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700436
Damien Neilea7baf42018-09-28 14:23:44 -0700437 genWellKnownType(g, "*", message.GoIdent, message.Desc)
438
Damien Neilebc699d2018-09-13 08:50:13 -0700439 // Constants and vars holding the default values of fields.
440 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800441 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700442 continue
443 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700444 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700445 def := field.Desc.Default()
446 switch field.Desc.Kind() {
447 case protoreflect.StringKind:
448 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
449 case protoreflect.BytesKind:
450 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
451 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700452 evalueDesc := field.Desc.DefaultEnumValue()
Joe Tsaid24bc722019-04-15 23:39:09 -0700453 enum := field.Enum
Damien Neila485fbd2018-10-26 13:28:37 -0700454 evalue := enum.Values[evalueDesc.Index()]
Joe Tsaid24bc722019-04-15 23:39:09 -0700455 g.P("const ", defVarName, " ", field.Enum.GoIdent, " = ", evalue.GoIdent)
Damien Neilebc699d2018-09-13 08:50:13 -0700456 case protoreflect.FloatKind, protoreflect.DoubleKind:
457 // Floating point numbers need extra handling for -Inf/Inf/NaN.
458 f := field.Desc.Default().Float()
459 goType := "float64"
460 if field.Desc.Kind() == protoreflect.FloatKind {
461 goType = "float32"
462 }
463 // funcCall returns a call to a function in the math package,
464 // possibly converting the result to float32.
465 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800466 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700467 if goType != "float64" {
468 s = goType + "(" + s + ")"
469 }
470 return s
471 }
472 switch {
473 case math.IsInf(f, -1):
474 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
475 case math.IsInf(f, 1):
476 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
477 case math.IsNaN(f):
478 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
479 default:
Damien Neil982684b2018-09-28 14:12:41 -0700480 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700481 }
482 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700483 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700484 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
485 }
486 }
487 g.P()
488
Joe Tsai61968ce2019-04-01 12:59:24 -0700489 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700490 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700491 if isFirstOneofField(field) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700492 genOneofGetter(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700493 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700494 goType, pointer := fieldGoType(g, field)
495 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800496 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700497 g.P(deprecationComment(true))
498 }
Damien Neil162c1272018-10-04 12:42:37 -0700499 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700500 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Joe Tsaid24bc722019-04-15 23:39:09 -0700501 if field.Oneof != nil {
502 g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700503 g.P("return x.", field.GoName)
504 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700505 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700506 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700507 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700508 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700509 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700510 }
511 star := ""
512 if pointer {
513 star = "*"
514 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700515 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700516 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700517 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700518 g.P("return ", defaultValue)
519 g.P("}")
520 g.P()
521 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700522
Joe Tsai872b5002019-04-08 14:03:15 -0700523 // XXX_OneofWrappers method.
Damien Neil1fa78d82018-09-13 13:12:36 -0700524 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800525 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700526 }
Joe Tsai872b5002019-04-08 14:03:15 -0700527
528 // Oneof wrapper types.
529 for _, oneof := range message.Oneofs {
530 genOneofTypes(gen, g, f, message, oneof)
531 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700532}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700533
Damien Neil77f82fe2018-09-13 10:59:17 -0700534// fieldGoType returns the Go type used for a field.
535//
536// If it returns pointer=true, the struct field is a pointer to the type.
537func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700538 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700539 switch field.Desc.Kind() {
540 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700541 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700542 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700543 goType = g.QualifiedGoIdent(field.Enum.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700544 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700545 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700546 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700547 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700548 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700549 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700550 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700551 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700552 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700553 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700554 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700555 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700556 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700557 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700558 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700559 goType = "[]byte"
560 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700561 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700562 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700563 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700564 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700565 switch {
566 case field.Desc.IsList():
Damien Neil77f82fe2018-09-13 10:59:17 -0700567 goType = "[]" + goType
568 pointer = false
Joe Tsaiac31a352019-05-13 14:32:56 -0700569 case field.Desc.IsMap():
570 keyType, _ := fieldGoType(g, field.Message.Fields[0])
571 valType, _ := fieldGoType(g, field.Message.Fields[1])
572 return fmt.Sprintf("map[%v]%v", keyType, valType), false
Damien Neil658051b2018-09-10 12:26:21 -0700573 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700574
Damien Neil44000a12018-10-24 12:31:16 -0700575 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaiac31a352019-05-13 14:32:56 -0700576 if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700577 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700578 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700579 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700580}
581
582func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700583 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700584 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700585 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700586 }
Joe Tsai05828db2018-11-01 13:52:16 -0700587 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700588}
589
Damien Neil77f82fe2018-09-13 10:59:17 -0700590func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
Joe Tsaiac31a352019-05-13 14:32:56 -0700591 if field.Desc.IsList() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700592 return "nil"
593 }
Joe Tsai9667c482018-12-05 15:42:52 -0800594 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700595 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700596 if field.Desc.Kind() == protoreflect.BytesKind {
597 return "append([]byte(nil), " + defVarName + "...)"
598 }
599 return defVarName
600 }
601 switch field.Desc.Kind() {
602 case protoreflect.BoolKind:
603 return "false"
604 case protoreflect.StringKind:
605 return `""`
606 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
607 return "nil"
608 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700609 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700610 default:
611 return "0"
612 }
613}
614
Damien Neil658051b2018-09-10 12:26:21 -0700615func fieldJSONTag(field *protogen.Field) string {
616 return string(field.Desc.Name()) + ",omitempty"
617}
618
Joe Tsaiafb455e2019-03-14 16:08:22 -0700619func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
620 if len(f.allExtensions) == 0 {
621 return
Damien Neil154da982018-09-19 13:21:58 -0700622 }
623
Joe Tsai4fddeba2019-03-20 18:29:32 -0700624 g.P("var ", extDecsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700625 for _, extension := range f.allExtensions {
626 // Special case for proto2 message sets: If this extension is extending
627 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
628 // then drop that last component.
629 //
630 // TODO: This should be implemented in the text formatter rather than the generator.
631 // In addition, the situation for when to apply this special case is implemented
632 // differently in other languages:
633 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
634 name := extension.Desc.FullName()
635 if n, ok := isExtensionMessageSetElement(extension); ok {
636 name = n
637 }
638
639 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700640 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700641 goType, pointer := fieldGoType(g, extension)
642 if pointer {
643 goType = "*" + goType
644 }
645 g.P("ExtensionType: (", goType, ")(nil),")
646 g.P("Field: ", extension.Desc.Number(), ",")
647 g.P("Name: ", strconv.Quote(string(name)), ",")
648 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
649 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
650 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700651 }
Damien Neil993c04d2018-09-14 15:41:11 -0700652 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700653
654 g.P("var (")
655 for i, extension := range f.allExtensions {
656 ed := extension.Desc
Joe Tsaiac31a352019-05-13 14:32:56 -0700657 targetName := string(ed.ContainingMessage().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700658 typeName := ed.Kind().String()
659 switch ed.Kind() {
660 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700661 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700662 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700663 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700664 }
665 fieldName := string(ed.Name())
666 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
667 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
668 g.P()
669 }
670 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700671}
672
Damien Neil62386962018-10-30 10:35:48 -0700673// isExtensionMessageSetELement returns the adjusted name of an extension
674// which extends proto2.bridge.MessageSet.
675func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700676 opts := extension.Extendee.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700677 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
678 return "", false
679 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700680 if extension.Parent == nil {
Damien Neil62386962018-10-30 10:35:48 -0700681 // This case shouldn't be given special handling at all--we're
682 // only supposed to drop the ".message_set_extension" for
683 // extensions defined within a message (i.e., the extension
684 // takes the message's name).
685 //
686 // This matches the behavior of the v1 generator, however.
687 //
688 // TODO: See if we can drop this case.
689 name = extension.Desc.FullName()
690 name = name[:len(name)-len("message_set_extension")]
691 return name, true
692 }
693 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700694}
695
Damien Neil993c04d2018-09-14 15:41:11 -0700696// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700697func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700698 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700699 if extension.Parent != nil {
700 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700701 }
702 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800703 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700704}
705
Damien Neil55fe1c02018-09-17 15:11:24 -0700706// deprecationComment returns a standard deprecation comment if deprecated is true.
707func deprecationComment(deprecated bool) string {
708 if !deprecated {
709 return ""
710 }
711 return "// Deprecated: Do not use."
712}
713
Damien Neil5c5b5312019-05-14 12:44:37 -0700714// TODO: Remove this. This was added to aid protojson, but protojson does this work
Joe Tsai61968ce2019-04-01 12:59:24 -0700715// through the use of protobuf reflection now.
Damien Neilea7baf42018-09-28 14:23:44 -0700716func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700717 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700718 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700719 g.P()
720 }
721}
722
723// Names of messages and enums for which we will generate XXX_WellKnownType methods.
724var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700725 "google.protobuf.Any": true,
726 "google.protobuf.Duration": true,
727 "google.protobuf.Empty": true,
728 "google.protobuf.Struct": true,
729 "google.protobuf.Timestamp": true,
730
731 "google.protobuf.BoolValue": true,
732 "google.protobuf.BytesValue": true,
733 "google.protobuf.DoubleValue": true,
734 "google.protobuf.FloatValue": true,
735 "google.protobuf.Int32Value": true,
736 "google.protobuf.Int64Value": true,
737 "google.protobuf.ListValue": true,
738 "google.protobuf.NullValue": true,
739 "google.protobuf.StringValue": true,
740 "google.protobuf.UInt32Value": true,
741 "google.protobuf.UInt64Value": true,
742 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700743}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800744
745// genOneofField generates the struct field for a oneof.
746func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
747 if g.PrintLeadingComments(oneof.Location) {
748 g.P("//")
749 }
750 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
751 for _, field := range oneof.Fields {
752 g.PrintLeadingComments(field.Location)
753 g.P("//\t*", fieldOneofType(field))
754 }
755 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
756 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
757}
758
Joe Tsai872b5002019-04-08 14:03:15 -0700759// genOneofGetter generate a Get method for a oneof.
760func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
761 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
762 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
763 g.P("if m != nil {")
764 g.P("return m.", oneofFieldName(oneof))
765 g.P("}")
766 g.P("return nil")
767 g.P("}")
768 g.P()
769}
770
771// genOneofWrappers generates the XXX_OneofWrappers method for a message.
772func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
773 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
774 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
775 g.P("return []interface{}{")
776 for _, oneof := range message.Oneofs {
777 for _, field := range oneof.Fields {
778 g.P("(*", fieldOneofType(field), ")(nil),")
779 }
780 }
781 g.P("}")
782 g.P("}")
783 g.P()
784}
785
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800786// genOneofTypes generates the interface type used for a oneof field,
787// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800788func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
789 ifName := oneofInterfaceName(oneof)
790 g.P("type ", ifName, " interface {")
791 g.P(ifName, "()")
792 g.P("}")
793 g.P()
794 for _, field := range oneof.Fields {
795 name := fieldOneofType(field)
796 g.Annotate(name.GoName, field.Location)
797 g.Annotate(name.GoName+"."+field.GoName, field.Location)
798 g.P("type ", name, " struct {")
799 goType, _ := fieldGoType(g, field)
800 tags := []string{
801 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
802 }
803 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
804 g.P("}")
805 g.P()
806 }
807 for _, field := range oneof.Fields {
808 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
809 g.P()
810 }
Joe Tsai872b5002019-04-08 14:03:15 -0700811}
812
813// isFirstOneofField reports whether this is the first field in a oneof.
814func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700815 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800816}
817
818// oneofFieldName returns the name of the struct field holding the oneof value.
819//
820// This function is trivial, but pulling out the name like this makes it easier
821// to experiment with alternative oneof implementations.
822func oneofFieldName(oneof *protogen.Oneof) string {
823 return oneof.GoName
824}
825
826// oneofInterfaceName returns the name of the interface type implemented by
827// the oneof field value types.
828func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700829 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800830}
831
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800832// fieldOneofType returns the wrapper type used to represent a field in a oneof.
833func fieldOneofType(field *protogen.Field) protogen.GoIdent {
834 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700835 GoImportPath: field.Parent.GoIdent.GoImportPath,
836 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800837 }
838 // Check for collisions with nested messages or enums.
839 //
840 // This conflict resolution is incomplete: Among other things, it
841 // does not consider collisions with other oneof field types.
842 //
843 // TODO: Consider dropping this entirely. Detecting conflicts and
844 // producing an error is almost certainly better than permuting
845 // field and type names in mostly unpredictable ways.
846Loop:
847 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700848 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800849 if message.GoIdent == ident {
850 ident.GoName += "_"
851 continue Loop
852 }
853 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700854 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800855 if enum.GoIdent == ident {
856 ident.GoName += "_"
857 continue Loop
858 }
859 }
860 return ident
861 }
862}