blob: 397467ae8781f9e7c8ff9d7f6453798272db1672 [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
Joe Tsaia95b29f2019-05-16 12:47:20 -070024 "google.golang.org/protobuf/types/descriptorpb"
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.
Joe Tsaidbab6c02019-05-14 15:06:03 -0700269 //
270 // NOTE: A pointer value is needed to represent presence in proto2.
271 // Since a proto2 message can reference a proto3 enum, it is useful to
272 // always generate this method (even on proto3 enums) to support that case.
273 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
274 g.P("p := new(", enum.GoIdent, ")")
275 g.P("*p = x")
276 g.P("return p")
277 g.P("}")
278 g.P()
279
Joe Tsai61968ce2019-04-01 12:59:24 -0700280 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700281 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700282 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700283 g.P("}")
284 g.P()
285
Joe Tsai61968ce2019-04-01 12:59:24 -0700286 genReflectEnum(gen, g, f, enum)
287
288 // UnmarshalJSON method.
Joe Tsai73903462018-12-14 12:22:41 -0800289 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700290 g.P("// Deprecated: Do not use.")
291 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700292 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700293 g.P("if err != nil {")
294 g.P("return err")
295 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700296 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700297 g.P("return nil")
298 g.P("}")
299 g.P()
300 }
301
Joe Tsai61968ce2019-04-01 12:59:24 -0700302 // EnumDescriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700303 if generateRawDescMethods {
304 var indexes []string
305 for i := 1; i < len(enum.Location.Path); i += 2 {
306 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
307 }
308 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
309 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
310 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
311 g.P("}")
312 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700313 }
Damien Neil46abb572018-09-07 12:45:37 -0700314
Damien Neilea7baf42018-09-28 14:23:44 -0700315 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700316}
317
Joe Tsai61968ce2019-04-01 12:59:24 -0700318// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700319//
320// Confusingly, this is <proto_package>.<go_ident>. This probably should have
321// been the full name of the proto enum type instead, but changing it at this
322// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700323func enumLegacyName(enum *protogen.Enum) string {
Joe Tsai67c1d9b2019-05-12 02:27:46 -0700324 fdesc := enum.Desc.ParentFile()
Damien Neildaa4fad2018-10-08 14:08:27 -0700325 if fdesc.Package() == "" {
326 return enum.GoIdent.GoName
327 }
Damien Neil658051b2018-09-10 12:26:21 -0700328 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
329}
330
Damien Neild39efc82018-09-24 12:38:10 -0700331func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700332 if message.Desc.IsMapEntry() {
333 return
334 }
335
Joe Tsai61968ce2019-04-01 12:59:24 -0700336 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700337 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800338 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700339 if hasComment {
340 g.P("//")
341 }
342 g.P(deprecationComment(true))
343 }
Damien Neil162c1272018-10-04 12:42:37 -0700344 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700345 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700346 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700347 if field.Oneof != nil {
Damien Neil1fa78d82018-09-13 13:12:36 -0700348 // It would be a bit simpler to iterate over the oneofs below,
349 // but generating the field here keeps the contents of the Go
350 // struct in the same order as the contents of the source
351 // .proto file.
Joe Tsaid24bc722019-04-15 23:39:09 -0700352 if field == field.Oneof.Fields[0] {
353 genOneofField(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700354 }
Damien Neil658051b2018-09-10 12:26:21 -0700355 continue
356 }
Damien Neilba1159f2018-10-17 12:53:18 -0700357 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700358 goType, pointer := fieldGoType(g, field)
359 if pointer {
360 goType = "*" + goType
361 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700362 tags := []string{
363 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
364 fmt.Sprintf("json:%q", fieldJSONTag(field)),
365 }
366 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700367 key := field.Message.Fields[0]
368 val := field.Message.Fields[1]
Damien Neil0bd5a382018-09-13 15:07:10 -0700369 tags = append(tags,
370 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
371 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
372 )
373 }
Damien Neil162c1272018-10-04 12:42:37 -0700374 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700375 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800376 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700377 }
378 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700379
380 if message.Desc.ExtensionRanges().Len() > 0 {
381 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800382 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700383 tags = append(tags, `protobuf_messageset:"1"`)
384 }
385 tags = append(tags, `json:"-"`)
Joe Tsai5e71dc92019-04-16 13:22:20 -0700386 g.P("XXX_InternalExtensions ", protoimplPackage.Ident("ExtensionFields"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700387 }
Joe Tsai5e71dc92019-04-16 13:22:20 -0700388 g.P("XXX_unrecognized ", protoimplPackage.Ident("UnknownFields"), " `json:\"-\"`")
389 g.P("XXX_sizecache ", protoimplPackage.Ident("SizeCache"), " `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700390 g.P("}")
391 g.P()
392
Joe Tsai61968ce2019-04-01 12:59:24 -0700393 // Reset method.
394 g.P("func (x *", message.GoIdent, ") Reset() {")
395 g.P("*x = ", message.GoIdent, "{}")
396 g.P("}")
397 g.P()
398 // String method.
399 g.P("func (x *", message.GoIdent, ") String() string {")
400 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
401 g.P("}")
402 g.P()
403 // ProtoMessage method.
404 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
405 g.P()
406
Joe Tsaib6405bd2018-11-15 14:44:37 -0800407 genReflectMessage(gen, g, f, message)
408
Joe Tsai61968ce2019-04-01 12:59:24 -0700409 // Descriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700410 if generateRawDescMethods {
411 var indexes []string
412 for i := 1; i < len(message.Location.Path); i += 2 {
413 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
414 }
415 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
416 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
417 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
418 g.P("}")
419 g.P()
Damien Neila1c6abc2018-09-12 13:36:34 -0700420 }
Damien Neil993c04d2018-09-14 15:41:11 -0700421
Joe Tsai61968ce2019-04-01 12:59:24 -0700422 // ExtensionRangeArray method.
Damien Neil993c04d2018-09-14 15:41:11 -0700423 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700424 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700425 extRangeVar := "extRange_" + message.GoIdent.GoName
426 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
427 for i := 0; i < extranges.Len(); i++ {
428 r := extranges.Get(i)
429 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
430 }
431 g.P("}")
432 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700433 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700434 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
435 g.P("return ", extRangeVar)
436 g.P("}")
437 g.P()
438 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700439
Damien Neilea7baf42018-09-28 14:23:44 -0700440 genWellKnownType(g, "*", message.GoIdent, message.Desc)
441
Damien Neilebc699d2018-09-13 08:50:13 -0700442 // Constants and vars holding the default values of fields.
443 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800444 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700445 continue
446 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700447 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700448 def := field.Desc.Default()
449 switch field.Desc.Kind() {
450 case protoreflect.StringKind:
451 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
452 case protoreflect.BytesKind:
453 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
454 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700455 evalueDesc := field.Desc.DefaultEnumValue()
Joe Tsaid24bc722019-04-15 23:39:09 -0700456 enum := field.Enum
Damien Neila485fbd2018-10-26 13:28:37 -0700457 evalue := enum.Values[evalueDesc.Index()]
Joe Tsaid24bc722019-04-15 23:39:09 -0700458 g.P("const ", defVarName, " ", field.Enum.GoIdent, " = ", evalue.GoIdent)
Damien Neilebc699d2018-09-13 08:50:13 -0700459 case protoreflect.FloatKind, protoreflect.DoubleKind:
460 // Floating point numbers need extra handling for -Inf/Inf/NaN.
461 f := field.Desc.Default().Float()
462 goType := "float64"
463 if field.Desc.Kind() == protoreflect.FloatKind {
464 goType = "float32"
465 }
466 // funcCall returns a call to a function in the math package,
467 // possibly converting the result to float32.
468 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800469 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700470 if goType != "float64" {
471 s = goType + "(" + s + ")"
472 }
473 return s
474 }
475 switch {
476 case math.IsInf(f, -1):
477 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
478 case math.IsInf(f, 1):
479 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
480 case math.IsNaN(f):
481 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
482 default:
Damien Neil982684b2018-09-28 14:12:41 -0700483 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700484 }
485 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700486 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700487 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
488 }
489 }
490 g.P()
491
Joe Tsai61968ce2019-04-01 12:59:24 -0700492 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700493 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700494 if isFirstOneofField(field) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700495 genOneofGetter(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700496 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700497 goType, pointer := fieldGoType(g, field)
498 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800499 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700500 g.P(deprecationComment(true))
501 }
Damien Neil162c1272018-10-04 12:42:37 -0700502 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700503 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Joe Tsaid24bc722019-04-15 23:39:09 -0700504 if field.Oneof != nil {
505 g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700506 g.P("return x.", field.GoName)
507 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700508 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700509 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700510 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700511 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700512 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700513 }
514 star := ""
515 if pointer {
516 star = "*"
517 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700518 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700519 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700520 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700521 g.P("return ", defaultValue)
522 g.P("}")
523 g.P()
524 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700525
Joe Tsai872b5002019-04-08 14:03:15 -0700526 // XXX_OneofWrappers method.
Damien Neil1fa78d82018-09-13 13:12:36 -0700527 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800528 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700529 }
Joe Tsai872b5002019-04-08 14:03:15 -0700530
531 // Oneof wrapper types.
532 for _, oneof := range message.Oneofs {
533 genOneofTypes(gen, g, f, message, oneof)
534 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700535}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700536
Damien Neil77f82fe2018-09-13 10:59:17 -0700537// fieldGoType returns the Go type used for a field.
538//
539// If it returns pointer=true, the struct field is a pointer to the type.
540func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700541 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700542 switch field.Desc.Kind() {
543 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700544 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700545 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700546 goType = g.QualifiedGoIdent(field.Enum.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700547 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700548 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700549 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700550 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700551 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700552 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700553 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700554 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700555 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700556 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700557 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700558 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700559 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700560 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700561 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700562 goType = "[]byte"
563 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700564 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700565 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700566 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700567 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700568 switch {
569 case field.Desc.IsList():
Damien Neil77f82fe2018-09-13 10:59:17 -0700570 goType = "[]" + goType
571 pointer = false
Joe Tsaiac31a352019-05-13 14:32:56 -0700572 case field.Desc.IsMap():
573 keyType, _ := fieldGoType(g, field.Message.Fields[0])
574 valType, _ := fieldGoType(g, field.Message.Fields[1])
575 return fmt.Sprintf("map[%v]%v", keyType, valType), false
Damien Neil658051b2018-09-10 12:26:21 -0700576 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700577
Damien Neil44000a12018-10-24 12:31:16 -0700578 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaiac31a352019-05-13 14:32:56 -0700579 if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700580 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700581 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700582 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700583}
584
585func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700586 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700587 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700588 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700589 }
Joe Tsai05828db2018-11-01 13:52:16 -0700590 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700591}
592
Damien Neil77f82fe2018-09-13 10:59:17 -0700593func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
Joe Tsaiac31a352019-05-13 14:32:56 -0700594 if field.Desc.IsList() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700595 return "nil"
596 }
Joe Tsai9667c482018-12-05 15:42:52 -0800597 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700598 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700599 if field.Desc.Kind() == protoreflect.BytesKind {
600 return "append([]byte(nil), " + defVarName + "...)"
601 }
602 return defVarName
603 }
604 switch field.Desc.Kind() {
605 case protoreflect.BoolKind:
606 return "false"
607 case protoreflect.StringKind:
608 return `""`
609 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
610 return "nil"
611 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700612 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700613 default:
614 return "0"
615 }
616}
617
Damien Neil658051b2018-09-10 12:26:21 -0700618func fieldJSONTag(field *protogen.Field) string {
619 return string(field.Desc.Name()) + ",omitempty"
620}
621
Joe Tsaiafb455e2019-03-14 16:08:22 -0700622func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
623 if len(f.allExtensions) == 0 {
624 return
Damien Neil154da982018-09-19 13:21:58 -0700625 }
626
Joe Tsai4fddeba2019-03-20 18:29:32 -0700627 g.P("var ", extDecsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700628 for _, extension := range f.allExtensions {
629 // Special case for proto2 message sets: If this extension is extending
630 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
631 // then drop that last component.
632 //
633 // TODO: This should be implemented in the text formatter rather than the generator.
634 // In addition, the situation for when to apply this special case is implemented
635 // differently in other languages:
636 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
637 name := extension.Desc.FullName()
638 if n, ok := isExtensionMessageSetElement(extension); ok {
639 name = n
640 }
641
642 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700643 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700644 goType, pointer := fieldGoType(g, extension)
645 if pointer {
646 goType = "*" + goType
647 }
648 g.P("ExtensionType: (", goType, ")(nil),")
649 g.P("Field: ", extension.Desc.Number(), ",")
650 g.P("Name: ", strconv.Quote(string(name)), ",")
651 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
652 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
653 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700654 }
Damien Neil993c04d2018-09-14 15:41:11 -0700655 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700656
657 g.P("var (")
658 for i, extension := range f.allExtensions {
659 ed := extension.Desc
Joe Tsaiac31a352019-05-13 14:32:56 -0700660 targetName := string(ed.ContainingMessage().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700661 typeName := ed.Kind().String()
662 switch ed.Kind() {
663 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700664 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700665 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700666 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700667 }
668 fieldName := string(ed.Name())
669 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
670 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
671 g.P()
672 }
673 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700674}
675
Damien Neil62386962018-10-30 10:35:48 -0700676// isExtensionMessageSetELement returns the adjusted name of an extension
677// which extends proto2.bridge.MessageSet.
678func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700679 opts := extension.Extendee.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700680 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
681 return "", false
682 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700683 if extension.Parent == nil {
Damien Neil62386962018-10-30 10:35:48 -0700684 // This case shouldn't be given special handling at all--we're
685 // only supposed to drop the ".message_set_extension" for
686 // extensions defined within a message (i.e., the extension
687 // takes the message's name).
688 //
689 // This matches the behavior of the v1 generator, however.
690 //
691 // TODO: See if we can drop this case.
692 name = extension.Desc.FullName()
693 name = name[:len(name)-len("message_set_extension")]
694 return name, true
695 }
696 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700697}
698
Damien Neil993c04d2018-09-14 15:41:11 -0700699// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700700func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700701 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700702 if extension.Parent != nil {
703 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700704 }
705 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800706 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700707}
708
Damien Neil55fe1c02018-09-17 15:11:24 -0700709// deprecationComment returns a standard deprecation comment if deprecated is true.
710func deprecationComment(deprecated bool) string {
711 if !deprecated {
712 return ""
713 }
714 return "// Deprecated: Do not use."
715}
716
Damien Neil5c5b5312019-05-14 12:44:37 -0700717// TODO: Remove this. This was added to aid protojson, but protojson does this work
Joe Tsai61968ce2019-04-01 12:59:24 -0700718// through the use of protobuf reflection now.
Damien Neilea7baf42018-09-28 14:23:44 -0700719func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700720 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700721 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700722 g.P()
723 }
724}
725
726// Names of messages and enums for which we will generate XXX_WellKnownType methods.
727var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700728 "google.protobuf.Any": true,
729 "google.protobuf.Duration": true,
730 "google.protobuf.Empty": true,
731 "google.protobuf.Struct": true,
732 "google.protobuf.Timestamp": true,
733
734 "google.protobuf.BoolValue": true,
735 "google.protobuf.BytesValue": true,
736 "google.protobuf.DoubleValue": true,
737 "google.protobuf.FloatValue": true,
738 "google.protobuf.Int32Value": true,
739 "google.protobuf.Int64Value": true,
740 "google.protobuf.ListValue": true,
741 "google.protobuf.NullValue": true,
742 "google.protobuf.StringValue": true,
743 "google.protobuf.UInt32Value": true,
744 "google.protobuf.UInt64Value": true,
745 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700746}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800747
748// genOneofField generates the struct field for a oneof.
749func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
750 if g.PrintLeadingComments(oneof.Location) {
751 g.P("//")
752 }
753 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
754 for _, field := range oneof.Fields {
755 g.PrintLeadingComments(field.Location)
756 g.P("//\t*", fieldOneofType(field))
757 }
758 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
759 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
760}
761
Joe Tsai872b5002019-04-08 14:03:15 -0700762// genOneofGetter generate a Get method for a oneof.
763func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
764 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
765 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
766 g.P("if m != nil {")
767 g.P("return m.", oneofFieldName(oneof))
768 g.P("}")
769 g.P("return nil")
770 g.P("}")
771 g.P()
772}
773
774// genOneofWrappers generates the XXX_OneofWrappers method for a message.
775func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
776 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
777 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
778 g.P("return []interface{}{")
779 for _, oneof := range message.Oneofs {
780 for _, field := range oneof.Fields {
781 g.P("(*", fieldOneofType(field), ")(nil),")
782 }
783 }
784 g.P("}")
785 g.P("}")
786 g.P()
787}
788
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800789// genOneofTypes generates the interface type used for a oneof field,
790// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800791func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
792 ifName := oneofInterfaceName(oneof)
793 g.P("type ", ifName, " interface {")
794 g.P(ifName, "()")
795 g.P("}")
796 g.P()
797 for _, field := range oneof.Fields {
798 name := fieldOneofType(field)
799 g.Annotate(name.GoName, field.Location)
800 g.Annotate(name.GoName+"."+field.GoName, field.Location)
801 g.P("type ", name, " struct {")
802 goType, _ := fieldGoType(g, field)
803 tags := []string{
804 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
805 }
806 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
807 g.P("}")
808 g.P()
809 }
810 for _, field := range oneof.Fields {
811 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
812 g.P()
813 }
Joe Tsai872b5002019-04-08 14:03:15 -0700814}
815
816// isFirstOneofField reports whether this is the first field in a oneof.
817func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700818 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800819}
820
821// oneofFieldName returns the name of the struct field holding the oneof value.
822//
823// This function is trivial, but pulling out the name like this makes it easier
824// to experiment with alternative oneof implementations.
825func oneofFieldName(oneof *protogen.Oneof) string {
826 return oneof.GoName
827}
828
829// oneofInterfaceName returns the name of the interface type implemented by
830// the oneof field value types.
831func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700832 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800833}
834
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800835// fieldOneofType returns the wrapper type used to represent a field in a oneof.
836func fieldOneofType(field *protogen.Field) protogen.GoIdent {
837 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700838 GoImportPath: field.Parent.GoIdent.GoImportPath,
839 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800840 }
841 // Check for collisions with nested messages or enums.
842 //
843 // This conflict resolution is incomplete: Among other things, it
844 // does not consider collisions with other oneof field types.
845 //
846 // TODO: Consider dropping this entirely. Detecting conflicts and
847 // producing an error is almost certainly better than permuting
848 // field and type names in mostly unpredictable ways.
849Loop:
850 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700851 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800852 if message.GoIdent == ident {
853 ident.GoName += "_"
854 continue Loop
855 }
856 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700857 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800858 if enum.GoIdent == ident {
859 ident.GoName += "_"
860 continue Loop
861 }
862 }
863 return ident
864 }
865}