blob: 9e11fb0ebf8ab54911b26fe4c54a4f92c5eb689f [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
Joe Tsai05828db2018-11-01 13:52:16 -070019 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsaica46d8c2019-03-20 16:51:09 -070020 "github.com/golang/protobuf/v2/internal/fieldnum"
Joe Tsai01ab2962018-09-21 17:44:00 -070021 "github.com/golang/protobuf/v2/protogen"
22 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080023
24 descriptorpb "github.com/golang/protobuf/v2/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")
Joe Tsai4fddeba2019-03-20 18:29:32 -070047 protoifacePackage = protogen.GoImportPath("github.com/golang/protobuf/v2/runtime/protoiface")
48 protoimplPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/runtime/protoimpl")
49 protoreflectPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/reflect/protoreflect")
50 protoregistryPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/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:
Damien Neil0bd5a382018-09-13 15:07:10 -0700562 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700563 keyType, _ := fieldGoType(g, field.Message.Fields[0])
564 valType, _ := fieldGoType(g, field.Message.Fields[1])
Damien Neil0bd5a382018-09-13 15:07:10 -0700565 return fmt.Sprintf("map[%v]%v", keyType, valType), false
566 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700567 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700568 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700569 }
570 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700571 goType = "[]" + goType
572 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700573 }
Damien Neil44000a12018-10-24 12:31:16 -0700574 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaid24bc722019-04-15 23:39:09 -0700575 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.Extendee() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700576 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700577 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700578 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700579}
580
581func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700582 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700583 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700584 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700585 }
Joe Tsai05828db2018-11-01 13:52:16 -0700586 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700587}
588
Damien Neil77f82fe2018-09-13 10:59:17 -0700589func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
590 if field.Desc.Cardinality() == protoreflect.Repeated {
591 return "nil"
592 }
Joe Tsai9667c482018-12-05 15:42:52 -0800593 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700594 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700595 if field.Desc.Kind() == protoreflect.BytesKind {
596 return "append([]byte(nil), " + defVarName + "...)"
597 }
598 return defVarName
599 }
600 switch field.Desc.Kind() {
601 case protoreflect.BoolKind:
602 return "false"
603 case protoreflect.StringKind:
604 return `""`
605 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
606 return "nil"
607 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700608 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700609 default:
610 return "0"
611 }
612}
613
Damien Neil658051b2018-09-10 12:26:21 -0700614func fieldJSONTag(field *protogen.Field) string {
615 return string(field.Desc.Name()) + ",omitempty"
616}
617
Joe Tsaiafb455e2019-03-14 16:08:22 -0700618func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
619 if len(f.allExtensions) == 0 {
620 return
Damien Neil154da982018-09-19 13:21:58 -0700621 }
622
Joe Tsai4fddeba2019-03-20 18:29:32 -0700623 g.P("var ", extDecsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700624 for _, extension := range f.allExtensions {
625 // Special case for proto2 message sets: If this extension is extending
626 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
627 // then drop that last component.
628 //
629 // TODO: This should be implemented in the text formatter rather than the generator.
630 // In addition, the situation for when to apply this special case is implemented
631 // differently in other languages:
632 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
633 name := extension.Desc.FullName()
634 if n, ok := isExtensionMessageSetElement(extension); ok {
635 name = n
636 }
637
638 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700639 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700640 goType, pointer := fieldGoType(g, extension)
641 if pointer {
642 goType = "*" + goType
643 }
644 g.P("ExtensionType: (", goType, ")(nil),")
645 g.P("Field: ", extension.Desc.Number(), ",")
646 g.P("Name: ", strconv.Quote(string(name)), ",")
647 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
648 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
649 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700650 }
Damien Neil993c04d2018-09-14 15:41:11 -0700651 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700652
653 g.P("var (")
654 for i, extension := range f.allExtensions {
655 ed := extension.Desc
Joe Tsaid24bc722019-04-15 23:39:09 -0700656 targetName := string(ed.Extendee().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700657 typeName := ed.Kind().String()
658 switch ed.Kind() {
659 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700660 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700661 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700662 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700663 }
664 fieldName := string(ed.Name())
665 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
666 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
667 g.P()
668 }
669 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700670}
671
Damien Neil62386962018-10-30 10:35:48 -0700672// isExtensionMessageSetELement returns the adjusted name of an extension
673// which extends proto2.bridge.MessageSet.
674func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700675 opts := extension.Extendee.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700676 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
677 return "", false
678 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700679 if extension.Parent == nil {
Damien Neil62386962018-10-30 10:35:48 -0700680 // This case shouldn't be given special handling at all--we're
681 // only supposed to drop the ".message_set_extension" for
682 // extensions defined within a message (i.e., the extension
683 // takes the message's name).
684 //
685 // This matches the behavior of the v1 generator, however.
686 //
687 // TODO: See if we can drop this case.
688 name = extension.Desc.FullName()
689 name = name[:len(name)-len("message_set_extension")]
690 return name, true
691 }
692 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700693}
694
Damien Neil993c04d2018-09-14 15:41:11 -0700695// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700696func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700697 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700698 if extension.Parent != nil {
699 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700700 }
701 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800702 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700703}
704
Damien Neil55fe1c02018-09-17 15:11:24 -0700705// deprecationComment returns a standard deprecation comment if deprecated is true.
706func deprecationComment(deprecated bool) string {
707 if !deprecated {
708 return ""
709 }
710 return "// Deprecated: Do not use."
711}
712
Joe Tsai61968ce2019-04-01 12:59:24 -0700713// TODO: Remove this. This was added to aid jsonpb, but jsonpb does this work
714// through the use of protobuf reflection now.
Damien Neilea7baf42018-09-28 14:23:44 -0700715func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700716 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700717 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700718 g.P()
719 }
720}
721
722// Names of messages and enums for which we will generate XXX_WellKnownType methods.
723var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700724 "google.protobuf.Any": true,
725 "google.protobuf.Duration": true,
726 "google.protobuf.Empty": true,
727 "google.protobuf.Struct": true,
728 "google.protobuf.Timestamp": true,
729
730 "google.protobuf.BoolValue": true,
731 "google.protobuf.BytesValue": true,
732 "google.protobuf.DoubleValue": true,
733 "google.protobuf.FloatValue": true,
734 "google.protobuf.Int32Value": true,
735 "google.protobuf.Int64Value": true,
736 "google.protobuf.ListValue": true,
737 "google.protobuf.NullValue": true,
738 "google.protobuf.StringValue": true,
739 "google.protobuf.UInt32Value": true,
740 "google.protobuf.UInt64Value": true,
741 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700742}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800743
744// genOneofField generates the struct field for a oneof.
745func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
746 if g.PrintLeadingComments(oneof.Location) {
747 g.P("//")
748 }
749 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
750 for _, field := range oneof.Fields {
751 g.PrintLeadingComments(field.Location)
752 g.P("//\t*", fieldOneofType(field))
753 }
754 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
755 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
756}
757
Joe Tsai872b5002019-04-08 14:03:15 -0700758// genOneofGetter generate a Get method for a oneof.
759func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
760 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
761 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
762 g.P("if m != nil {")
763 g.P("return m.", oneofFieldName(oneof))
764 g.P("}")
765 g.P("return nil")
766 g.P("}")
767 g.P()
768}
769
770// genOneofWrappers generates the XXX_OneofWrappers method for a message.
771func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
772 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
773 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
774 g.P("return []interface{}{")
775 for _, oneof := range message.Oneofs {
776 for _, field := range oneof.Fields {
777 g.P("(*", fieldOneofType(field), ")(nil),")
778 }
779 }
780 g.P("}")
781 g.P("}")
782 g.P()
783}
784
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800785// genOneofTypes generates the interface type used for a oneof field,
786// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800787func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
788 ifName := oneofInterfaceName(oneof)
789 g.P("type ", ifName, " interface {")
790 g.P(ifName, "()")
791 g.P("}")
792 g.P()
793 for _, field := range oneof.Fields {
794 name := fieldOneofType(field)
795 g.Annotate(name.GoName, field.Location)
796 g.Annotate(name.GoName+"."+field.GoName, field.Location)
797 g.P("type ", name, " struct {")
798 goType, _ := fieldGoType(g, field)
799 tags := []string{
800 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
801 }
802 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
803 g.P("}")
804 g.P()
805 }
806 for _, field := range oneof.Fields {
807 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
808 g.P()
809 }
Joe Tsai872b5002019-04-08 14:03:15 -0700810}
811
812// isFirstOneofField reports whether this is the first field in a oneof.
813func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700814 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800815}
816
817// oneofFieldName returns the name of the struct field holding the oneof value.
818//
819// This function is trivial, but pulling out the name like this makes it easier
820// to experiment with alternative oneof implementations.
821func oneofFieldName(oneof *protogen.Oneof) string {
822 return oneof.GoName
823}
824
825// oneofInterfaceName returns the name of the interface type implemented by
826// the oneof field value types.
827func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700828 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800829}
830
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800831// fieldOneofType returns the wrapper type used to represent a field in a oneof.
832func fieldOneofType(field *protogen.Field) protogen.GoIdent {
833 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700834 GoImportPath: field.Parent.GoIdent.GoImportPath,
835 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800836 }
837 // Check for collisions with nested messages or enums.
838 //
839 // This conflict resolution is incomplete: Among other things, it
840 // does not consider collisions with other oneof field types.
841 //
842 // TODO: Consider dropping this entirely. Detecting conflicts and
843 // producing an error is almost certainly better than permuting
844 // field and type names in mostly unpredictable ways.
845Loop:
846 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700847 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800848 if message.GoIdent == ident {
849 ident.GoName += "_"
850 continue Loop
851 }
852 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700853 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800854 if enum.GoIdent == ident {
855 ident.GoName += "_"
856 continue Loop
857 }
858 }
859 return ident
860 }
861}