blob: e842e6ee3c0a137e5c9cbbdefa431c62ae11a2df [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 "crypto/sha256"
10 "encoding/hex"
11 "fmt"
Damien Neil7bf3ce22018-12-21 15:54:06 -080012 "go/ast"
13 "go/parser"
14 "go/token"
Damien Neilebc699d2018-09-13 08:50:13 -070015 "math"
Damien Neilce36f8d2018-09-13 15:19:08 -070016 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070017 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070018 "strings"
Damien Neil7bf3ce22018-12-21 15:54:06 -080019 "unicode"
20 "unicode/utf8"
Damien Neil7779e052018-09-07 14:14:06 -070021
22 "github.com/golang/protobuf/proto"
Joe Tsai05828db2018-11-01 13:52:16 -070023 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai01ab2962018-09-21 17:44:00 -070024 "github.com/golang/protobuf/v2/protogen"
25 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080026
27 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070028)
29
Damien Neild4127922018-09-12 11:13:49 -070030// generatedCodeVersion indicates a version of the generated code.
31// It is incremented whenever an incompatibility between the generated code and
32// proto package is introduced; the generated code references
33// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
Joe Tsaid7e97bc2018-11-26 12:57:27 -080034const generatedCodeVersion = 3
Damien Neild4127922018-09-12 11:13:49 -070035
Joe Tsaic1c17aa2018-11-16 11:14:14 -080036const (
Damien Neil8012b442019-01-18 09:32:24 -080037 bytesPackage = protogen.GoImportPath("bytes")
38 gzipPackage = protogen.GoImportPath("compress/gzip")
Joe Tsai24ceb2b2018-12-04 22:53:56 -080039 mathPackage = protogen.GoImportPath("math")
40 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
41 protoapiPackage = protogen.GoImportPath("github.com/golang/protobuf/protoapi")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080042)
Damien Neil46abb572018-09-07 12:45:37 -070043
Damien Neild39efc82018-09-24 12:38:10 -070044type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070045 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080046
47 // vars containing the raw wire-encoded and compressed FileDescriptorProto.
48 descriptorRawVar string
49 descriptorGzipVar string
Joe Tsaib6405bd2018-11-15 14:44:37 -080050
Joe Tsai9667c482018-12-05 15:42:52 -080051 allEnums []*protogen.Enum
52 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
53 allMessages []*protogen.Message
54 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
55 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070056}
57
Joe Tsai24ceb2b2018-12-04 22:53:56 -080058// protoPackage returns the package to import, which is either the protoPackage
59// or the protoapiPackage constant.
60//
61// This special casing exists because we are unable to move InternalMessageInfo
62// to protoapi since the implementation behind that logic is heavy and
63// too intricately connected to other parts of the proto package.
64// The descriptor proto is special in that it avoids using InternalMessageInfo
65// so that it is able to depend solely on protoapi and break its dependency
66// on the proto package. It is still semantically correct for descriptor to
67// avoid using InternalMessageInfo, but it does incur some performance penalty.
68// This is acceptable for descriptor, which is a single proto file and is not
69// known to be in the hot path for any code.
70//
71// TODO: Remove this special-casing when the table-driven implementation has
72// been ported over to v2.
73func (f *fileInfo) protoPackage() protogen.GoImportPath {
74 if isDescriptor(f.File) {
75 return protoapiPackage
76 }
77 return protoPackage
78}
79
Damien Neil9c420a62018-09-27 15:26:33 -070080// GenerateFile generates the contents of a .pb.go file.
81func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070082 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070083 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070084 }
85
Damien Neil8012b442019-01-18 09:32:24 -080086 // Collect all enums, messages, and extensions in "flattened ordering".
87 // See fileinit.FileBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080088 f.allEnums = append(f.allEnums, f.Enums...)
89 f.allMessages = append(f.allMessages, f.Messages...)
90 f.allExtensions = append(f.allExtensions, f.Extensions...)
91 walkMessages(f.Messages, func(m *protogen.Message) {
92 f.allEnums = append(f.allEnums, m.Enums...)
93 f.allMessages = append(f.allMessages, m.Messages...)
94 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070095 })
Damien Neilce36f8d2018-09-13 15:19:08 -070096
Joe Tsai9667c482018-12-05 15:42:52 -080097 // Derive a reverse mapping of enum and message pointers to their index
98 // in allEnums and allMessages.
99 if len(f.allEnums) > 0 {
100 f.allEnumsByPtr = make(map[*protogen.Enum]int)
101 for i, e := range f.allEnums {
102 f.allEnumsByPtr[e] = i
103 }
104 }
105 if len(f.allMessages) > 0 {
106 f.allMessagesByPtr = make(map[*protogen.Message]int)
107 for i, m := range f.allMessages {
108 f.allMessagesByPtr[m] = i
109 }
110 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800111
Damien Neil46abb572018-09-07 12:45:37 -0700112 // Determine the name of the var holding the file descriptor:
113 //
114 // fileDescriptor_<hash of filename>
115 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
Damien Neil8012b442019-01-18 09:32:24 -0800116 f.descriptorRawVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
117 f.descriptorGzipVar = f.descriptorRawVar + "_gzipped"
Damien Neil46abb572018-09-07 12:45:37 -0700118
Damien Neil220c2022018-08-15 11:24:18 -0700119 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700120 if f.Proto.GetOptions().GetDeprecated() {
121 g.P("// ", f.Desc.Path(), " is a deprecated file.")
122 } else {
123 g.P("// source: ", f.Desc.Path())
124 }
Damien Neil220c2022018-08-15 11:24:18 -0700125 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -0700126 const filePackageField = 2 // FileDescriptorProto.package
Damien Neilba1159f2018-10-17 12:53:18 -0700127 g.PrintLeadingComments(protogen.Location{
128 SourceFile: f.Proto.GetName(),
129 Path: []int32{filePackageField},
130 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700131 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700132 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700133 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700134
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800135 if !isDescriptor(file) {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800136 g.P("// This is a compile-time assertion to ensure that this generated file")
137 g.P("// is compatible with the proto package it is being compiled against.")
138 g.P("// A compilation error at this line likely means your copy of the")
139 g.P("// proto package needs to be updated.")
140 g.P("const _ = ", protoPackage.Ident(fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion)),
141 "// please upgrade the proto package")
142 g.P()
143 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700144
Damien Neil73ac8852018-09-17 15:11:24 -0700145 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
146 genImport(gen, g, f, imps.Get(i))
147 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700148 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700149 genEnum(gen, g, f, enum)
150 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700151 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700152 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700153 }
Joe Tsai9667c482018-12-05 15:42:52 -0800154 for _, extension := range f.allExtensions {
Damien Neil993c04d2018-09-14 15:41:11 -0700155 genExtension(gen, g, f, extension)
156 }
Damien Neil220c2022018-08-15 11:24:18 -0700157
Damien Neilce36f8d2018-09-13 15:19:08 -0700158 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700159 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800160 genReflectFileDescriptor(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700161}
162
Damien Neil73ac8852018-09-17 15:11:24 -0700163// walkMessages calls f on each message and all of its descendants.
164func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
165 for _, m := range messages {
166 f(m)
167 walkMessages(m.Messages, f)
168 }
169}
170
Damien Neild39efc82018-09-24 12:38:10 -0700171func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700172 impFile, ok := gen.FileByName(imp.Path())
173 if !ok {
174 return
175 }
176 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700177 // Don't generate imports or aliases for types in the same Go package.
178 return
179 }
Damien Neil40a08052018-10-29 09:07:41 -0700180 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700181 // referenced, because other code and tools depend on having the
182 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700183 if !imp.IsWeak {
184 g.Import(impFile.GoImportPath)
185 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700186 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700187 return
188 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800189
190 // Generate public imports by generating the imported file, parsing it,
191 // and extracting every symbol that should receive a forwarding declaration.
192 impGen := gen.NewGeneratedFile("temp.go", impFile.GoImportPath)
193 impGen.Skip()
194 GenerateFile(gen, impFile, impGen)
195 b, err := impGen.Content()
196 if err != nil {
197 gen.Error(err)
198 return
199 }
200 fset := token.NewFileSet()
201 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
202 if err != nil {
203 gen.Error(err)
204 return
205 }
Damien Neila7cbd062019-01-06 16:29:14 -0800206 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800207 // Don't import unexported symbols.
208 r, _ := utf8.DecodeRuneInString(name)
209 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700210 return
211 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800212 // Don't import the FileDescriptor.
213 if name == impFile.GoDescriptorIdent.GoName {
214 return
215 }
Damien Neila7cbd062019-01-06 16:29:14 -0800216 // Don't import decls referencing a symbol defined in another package.
217 // i.e., don't import decls which are themselves public imports:
218 //
219 // type T = somepackage.T
220 if _, ok := expr.(*ast.SelectorExpr); ok {
221 return
222 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800223 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
224 }
225 g.P("// Symbols defined in public import of ", imp.Path())
226 g.P()
227 for _, decl := range astFile.Decls {
228 switch decl := decl.(type) {
229 case *ast.GenDecl:
230 for _, spec := range decl.Specs {
231 switch spec := spec.(type) {
232 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800233 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800234 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800235 for i, name := range spec.Names {
236 var expr ast.Expr
237 if i < len(spec.Values) {
238 expr = spec.Values[i]
239 }
240 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800241 }
242 case *ast.ImportSpec:
243 default:
244 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800245 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700246 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700247 }
Damien Neil6b541312018-10-29 09:14:14 -0700248 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700249 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700250}
251
Damien Neild39efc82018-09-24 12:38:10 -0700252func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700253 // Trim the source_code_info from the descriptor.
254 // Marshal and gzip it.
Joe Tsaie1f8d502018-11-26 18:55:29 -0800255 descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto)
Damien Neil7779e052018-09-07 14:14:06 -0700256 descProto.SourceCodeInfo = nil
257 b, err := proto.Marshal(descProto)
258 if err != nil {
259 gen.Error(err)
260 return
261 }
Damien Neil7779e052018-09-07 14:14:06 -0700262
Damien Neil8012b442019-01-18 09:32:24 -0800263 g.P("var ", f.descriptorRawVar, " = []byte{")
264 g.P("// ", len(b), " bytes of the wire-encoded FileDescriptorProto")
Damien Neil7779e052018-09-07 14:14:06 -0700265 for len(b) > 0 {
266 n := 16
267 if n > len(b) {
268 n = len(b)
269 }
270
271 s := ""
272 for _, c := range b[:n] {
273 s += fmt.Sprintf("0x%02x,", c)
274 }
275 g.P(s)
276
277 b = b[n:]
278 }
279 g.P("}")
280 g.P()
Damien Neil8012b442019-01-18 09:32:24 -0800281
282 // TODO: Add a helper function in protoapi or protoimpl?
283 // This function would probably encode the input lazily upon first use.
284 // Currently, the GZIPed form is used eagerly in v1 registration.
285 // See https://play.golang.org/p/_atJHs0izTH
286 g.P("var ", f.descriptorGzipVar, " = func() []byte {")
287 g.P("bb := new(", bytesPackage.Ident("Buffer"), ")")
288 g.P("zw, _ := ", gzipPackage.Ident("NewWriterLevel"), "(bb, ", gzipPackage.Ident("NoCompression"), ")")
289 g.P("zw.Write(", f.descriptorRawVar, ")")
290 g.P("zw.Close()")
291 g.P("return bb.Bytes()")
292 g.P("}()")
293 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700294}
Damien Neilc7d07d92018-08-22 13:46:02 -0700295
Damien Neild39efc82018-09-24 12:38:10 -0700296func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700297 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700298 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700299 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800300 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700301 g.P("const (")
302 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700303 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700304 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700305 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800306 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700307 }
308 g.P(")")
309 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800310
311 // Generate support for protobuf reflection.
312 genReflectEnum(gen, g, f, enum)
313
Damien Neil46abb572018-09-07 12:45:37 -0700314 nameMap := enum.GoIdent.GoName + "_name"
315 g.P("var ", nameMap, " = map[int32]string{")
316 generated := make(map[protoreflect.EnumNumber]bool)
317 for _, value := range enum.Values {
318 duplicate := ""
319 if _, present := generated[value.Desc.Number()]; present {
320 duplicate = "// Duplicate value: "
321 }
322 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
323 generated[value.Desc.Number()] = true
324 }
325 g.P("}")
326 g.P()
327 valueMap := enum.GoIdent.GoName + "_value"
328 g.P("var ", valueMap, " = map[string]int32{")
329 for _, value := range enum.Values {
330 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
331 }
332 g.P("}")
333 g.P()
334 if enum.Desc.Syntax() != protoreflect.Proto3 {
335 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
336 g.P("p := new(", enum.GoIdent, ")")
337 g.P("*p = x")
338 g.P("return p")
339 g.P("}")
340 g.P()
341 }
342 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800343 g.P("return ", f.protoPackage().Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700344 g.P("}")
345 g.P()
346
Joe Tsai73903462018-12-14 12:22:41 -0800347 if enum.Desc.Syntax() == protoreflect.Proto2 {
Damien Neil46abb572018-09-07 12:45:37 -0700348 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800349 g.P("value, err := ", f.protoPackage().Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700350 g.P("if err != nil {")
351 g.P("return err")
352 g.P("}")
353 g.P("*x = ", enum.GoIdent, "(value)")
354 g.P("return nil")
355 g.P("}")
356 g.P()
357 }
358
359 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700360 for i := 1; i < len(enum.Location.Path); i += 2 {
361 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700362 }
363 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800364 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neil46abb572018-09-07 12:45:37 -0700365 g.P("}")
366 g.P()
367
Damien Neilea7baf42018-09-28 14:23:44 -0700368 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700369}
370
Damien Neil658051b2018-09-10 12:26:21 -0700371// enumRegistryName returns the name used to register an enum with the proto
372// package registry.
373//
374// Confusingly, this is <proto_package>.<go_ident>. This probably should have
375// been the full name of the proto enum type instead, but changing it at this
376// point would require thought.
377func enumRegistryName(enum *protogen.Enum) string {
378 // Find the FileDescriptor for this enum.
379 var desc protoreflect.Descriptor = enum.Desc
380 for {
381 p, ok := desc.Parent()
382 if !ok {
383 break
384 }
385 desc = p
386 }
387 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700388 if fdesc.Package() == "" {
389 return enum.GoIdent.GoName
390 }
Damien Neil658051b2018-09-10 12:26:21 -0700391 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
392}
393
Damien Neild39efc82018-09-24 12:38:10 -0700394func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700395 if message.Desc.IsMapEntry() {
396 return
397 }
398
Damien Neilba1159f2018-10-17 12:53:18 -0700399 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800400 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700401 if hasComment {
402 g.P("//")
403 }
404 g.P(deprecationComment(true))
405 }
Damien Neil162c1272018-10-04 12:42:37 -0700406 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700407 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700408 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700409 if field.OneofType != nil {
410 // It would be a bit simpler to iterate over the oneofs below,
411 // but generating the field here keeps the contents of the Go
412 // struct in the same order as the contents of the source
413 // .proto file.
414 if field == field.OneofType.Fields[0] {
415 genOneofField(gen, g, f, message, field.OneofType)
416 }
Damien Neil658051b2018-09-10 12:26:21 -0700417 continue
418 }
Damien Neilba1159f2018-10-17 12:53:18 -0700419 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700420 goType, pointer := fieldGoType(g, field)
421 if pointer {
422 goType = "*" + goType
423 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700424 tags := []string{
425 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
426 fmt.Sprintf("json:%q", fieldJSONTag(field)),
427 }
428 if field.Desc.IsMap() {
429 key := field.MessageType.Fields[0]
430 val := field.MessageType.Fields[1]
431 tags = append(tags,
432 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
433 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
434 )
435 }
Damien Neil162c1272018-10-04 12:42:37 -0700436 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700437 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800438 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700439 }
440 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700441
442 if message.Desc.ExtensionRanges().Len() > 0 {
443 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800444 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700445 tags = append(tags, `protobuf_messageset:"1"`)
446 }
447 tags = append(tags, `json:"-"`)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800448 g.P(f.protoPackage().Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700449 }
Damien Neil658051b2018-09-10 12:26:21 -0700450 g.P("XXX_unrecognized []byte `json:\"-\"`")
451 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700452 g.P("}")
453 g.P()
454
Joe Tsaib6405bd2018-11-15 14:44:37 -0800455 // Generate support for protobuf reflection.
456 genReflectMessage(gen, g, f, message)
457
Damien Neila1c6abc2018-09-12 13:36:34 -0700458 // Reset
459 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
460 // String
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800461 g.P("func (m *", message.GoIdent, ") String() string { return ", f.protoPackage().Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700462 // ProtoMessage
463 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
464 // Descriptor
465 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700466 for i := 1; i < len(message.Location.Path); i += 2 {
467 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700468 }
469 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800470 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neila1c6abc2018-09-12 13:36:34 -0700471 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700472 g.P()
473
474 // ExtensionRangeArray
475 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800476 protoExtRange := f.protoPackage().Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700477 extRangeVar := "extRange_" + message.GoIdent.GoName
478 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
479 for i := 0; i < extranges.Len(); i++ {
480 r := extranges.Get(i)
481 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
482 }
483 g.P("}")
484 g.P()
485 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
486 g.P("return ", extRangeVar)
487 g.P("}")
488 g.P()
489 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700490
Damien Neilea7baf42018-09-28 14:23:44 -0700491 genWellKnownType(g, "*", message.GoIdent, message.Desc)
492
Damien Neila1c6abc2018-09-12 13:36:34 -0700493 // Table-driven proto support.
494 //
495 // TODO: It does not scale to keep adding another method for every
496 // operation on protos that we want to switch over to using the
497 // table-driven approach. Instead, we should only add a single method
498 // that allows getting access to the *InternalMessageInfo struct and then
499 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800500 if !isDescriptor(f.File) {
501 // NOTE: We avoid adding table-driven support for descriptor proto
502 // since this depends on the v1 proto package, which would eventually
503 // need to depend on the descriptor itself.
504 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
505 // XXX_Unmarshal
506 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
507 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
508 g.P("}")
509 // XXX_Marshal
510 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
511 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
512 g.P("}")
513 // XXX_Merge
514 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
515 g.P(messageInfoVar, ".Merge(m, src)")
516 g.P("}")
517 // XXX_Size
518 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
519 g.P("return ", messageInfoVar, ".Size(m)")
520 g.P("}")
521 // XXX_DiscardUnknown
522 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
523 g.P(messageInfoVar, ".DiscardUnknown(m)")
524 g.P("}")
525 g.P()
526 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
527 g.P()
528 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700529
Damien Neilebc699d2018-09-13 08:50:13 -0700530 // Constants and vars holding the default values of fields.
531 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800532 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700533 continue
534 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700535 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700536 def := field.Desc.Default()
537 switch field.Desc.Kind() {
538 case protoreflect.StringKind:
539 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
540 case protoreflect.BytesKind:
541 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
542 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700543 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700544 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700545 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700546 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
547 case protoreflect.FloatKind, protoreflect.DoubleKind:
548 // Floating point numbers need extra handling for -Inf/Inf/NaN.
549 f := field.Desc.Default().Float()
550 goType := "float64"
551 if field.Desc.Kind() == protoreflect.FloatKind {
552 goType = "float32"
553 }
554 // funcCall returns a call to a function in the math package,
555 // possibly converting the result to float32.
556 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800557 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700558 if goType != "float64" {
559 s = goType + "(" + s + ")"
560 }
561 return s
562 }
563 switch {
564 case math.IsInf(f, -1):
565 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
566 case math.IsInf(f, 1):
567 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
568 case math.IsNaN(f):
569 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
570 default:
Damien Neil982684b2018-09-28 14:12:41 -0700571 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700572 }
573 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700574 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700575 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
576 }
577 }
578 g.P()
579
Damien Neil77f82fe2018-09-13 10:59:17 -0700580 // Getters.
581 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700582 if field.OneofType != nil {
583 if field == field.OneofType.Fields[0] {
584 genOneofTypes(gen, g, f, message, field.OneofType)
585 }
586 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700587 goType, pointer := fieldGoType(g, field)
588 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800589 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700590 g.P(deprecationComment(true))
591 }
Damien Neil162c1272018-10-04 12:42:37 -0700592 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700593 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
594 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700595 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700596 g.P("return x.", field.GoName)
597 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700598 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700599 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
600 g.P("if m != nil {")
601 } else {
602 g.P("if m != nil && m.", field.GoName, " != nil {")
603 }
604 star := ""
605 if pointer {
606 star = "*"
607 }
608 g.P("return ", star, " m.", field.GoName)
609 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700610 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700611 g.P("return ", defaultValue)
612 g.P("}")
613 g.P()
614 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700615
Damien Neil1fa78d82018-09-13 13:12:36 -0700616 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800617 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700618 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700619}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700620
Damien Neil77f82fe2018-09-13 10:59:17 -0700621// fieldGoType returns the Go type used for a field.
622//
623// If it returns pointer=true, the struct field is a pointer to the type.
624func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700625 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700626 switch field.Desc.Kind() {
627 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700629 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700631 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700632 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700633 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700634 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700635 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700636 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700637 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700638 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700639 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700640 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700641 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700642 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700643 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700644 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700645 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700646 goType = "[]byte"
647 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700648 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700649 if field.Desc.IsMap() {
650 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
651 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
652 return fmt.Sprintf("map[%v]%v", keyType, valType), false
653 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700654 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
655 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700656 }
657 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700658 goType = "[]" + goType
659 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700660 }
Damien Neil44000a12018-10-24 12:31:16 -0700661 // Extension fields always have pointer type, even when defined in a proto3 file.
662 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700663 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700664 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700665 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700666}
667
668func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700669 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700670 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700671 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700672 }
Joe Tsai05828db2018-11-01 13:52:16 -0700673 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700674}
675
Damien Neil77f82fe2018-09-13 10:59:17 -0700676func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
677 if field.Desc.Cardinality() == protoreflect.Repeated {
678 return "nil"
679 }
Joe Tsai9667c482018-12-05 15:42:52 -0800680 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700681 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700682 if field.Desc.Kind() == protoreflect.BytesKind {
683 return "append([]byte(nil), " + defVarName + "...)"
684 }
685 return defVarName
686 }
687 switch field.Desc.Kind() {
688 case protoreflect.BoolKind:
689 return "false"
690 case protoreflect.StringKind:
691 return `""`
692 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
693 return "nil"
694 case protoreflect.EnumKind:
695 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
696 default:
697 return "0"
698 }
699}
700
Damien Neil658051b2018-09-10 12:26:21 -0700701func fieldJSONTag(field *protogen.Field) string {
702 return string(field.Desc.Name()) + ",omitempty"
703}
704
Damien Neild39efc82018-09-24 12:38:10 -0700705func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700706 // Special case for proto2 message sets: If this extension is extending
707 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
708 // then drop that last component.
709 //
710 // TODO: This should be implemented in the text formatter rather than the generator.
711 // In addition, the situation for when to apply this special case is implemented
712 // differently in other languages:
713 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
714 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700715 if n, ok := isExtensionMessageSetElement(extension); ok {
716 name = n
Damien Neil154da982018-09-19 13:21:58 -0700717 }
718
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800719 g.P("var ", extensionVar(f.File, extension), " = &", f.protoPackage().Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700720 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
721 goType, pointer := fieldGoType(g, extension)
722 if pointer {
723 goType = "*" + goType
724 }
725 g.P("ExtensionType: (", goType, ")(nil),")
726 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700727 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700728 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
729 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
730 g.P("}")
731 g.P()
732}
733
Damien Neil62386962018-10-30 10:35:48 -0700734// isExtensionMessageSetELement returns the adjusted name of an extension
735// which extends proto2.bridge.MessageSet.
736func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800737 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700738 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
739 return "", false
740 }
741 if extension.ParentMessage == nil {
742 // This case shouldn't be given special handling at all--we're
743 // only supposed to drop the ".message_set_extension" for
744 // extensions defined within a message (i.e., the extension
745 // takes the message's name).
746 //
747 // This matches the behavior of the v1 generator, however.
748 //
749 // TODO: See if we can drop this case.
750 name = extension.Desc.FullName()
751 name = name[:len(name)-len("message_set_extension")]
752 return name, true
753 }
754 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700755}
756
Damien Neil993c04d2018-09-14 15:41:11 -0700757// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700758func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700759 name := "E_"
760 if extension.ParentMessage != nil {
761 name += extension.ParentMessage.GoIdent.GoName + "_"
762 }
763 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800764 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700765}
766
Damien Neilce36f8d2018-09-13 15:19:08 -0700767// genInitFunction generates an init function that registers the types in the
768// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700769func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neilce36f8d2018-09-13 15:19:08 -0700770 g.P("func init() {")
Damien Neil8012b442019-01-18 09:32:24 -0800771 g.P(f.protoPackage().Ident("RegisterFile"), "(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorGzipVar, ")")
Damien Neil154da982018-09-19 13:21:58 -0700772 for _, enum := range f.allEnums {
773 name := enum.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800774 g.P(f.protoPackage().Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700775 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700776 for _, message := range f.allMessages {
777 if message.Desc.IsMapEntry() {
778 continue
779 }
780
781 name := message.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800782 g.P(f.protoPackage().Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700783
784 // Types of map fields, sorted by the name of the field message type.
785 var mapFields []*protogen.Field
786 for _, field := range message.Fields {
787 if field.Desc.IsMap() {
788 mapFields = append(mapFields, field)
789 }
790 }
791 sort.Slice(mapFields, func(i, j int) bool {
792 ni := mapFields[i].MessageType.Desc.FullName()
793 nj := mapFields[j].MessageType.Desc.FullName()
794 return ni < nj
795 })
796 for _, field := range mapFields {
797 typeName := string(field.MessageType.Desc.FullName())
798 goType, _ := fieldGoType(g, field)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800799 g.P(f.protoPackage().Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700800 }
801 }
Joe Tsai9667c482018-12-05 15:42:52 -0800802 for _, extension := range f.allExtensions {
803 g.P(f.protoPackage().Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil993c04d2018-09-14 15:41:11 -0700804 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700805 g.P("}")
806 g.P()
807}
808
Damien Neil55fe1c02018-09-17 15:11:24 -0700809// deprecationComment returns a standard deprecation comment if deprecated is true.
810func deprecationComment(deprecated bool) string {
811 if !deprecated {
812 return ""
813 }
814 return "// Deprecated: Do not use."
815}
816
Damien Neilea7baf42018-09-28 14:23:44 -0700817func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700818 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700819 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700820 g.P()
821 }
822}
823
824// Names of messages and enums for which we will generate XXX_WellKnownType methods.
825var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700826 "google.protobuf.Any": true,
827 "google.protobuf.Duration": true,
828 "google.protobuf.Empty": true,
829 "google.protobuf.Struct": true,
830 "google.protobuf.Timestamp": true,
831
832 "google.protobuf.BoolValue": true,
833 "google.protobuf.BytesValue": true,
834 "google.protobuf.DoubleValue": true,
835 "google.protobuf.FloatValue": true,
836 "google.protobuf.Int32Value": true,
837 "google.protobuf.Int64Value": true,
838 "google.protobuf.ListValue": true,
839 "google.protobuf.NullValue": true,
840 "google.protobuf.StringValue": true,
841 "google.protobuf.UInt32Value": true,
842 "google.protobuf.UInt64Value": true,
843 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700844}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800845
846// genOneofField generates the struct field for a oneof.
847func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
848 if g.PrintLeadingComments(oneof.Location) {
849 g.P("//")
850 }
851 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
852 for _, field := range oneof.Fields {
853 g.PrintLeadingComments(field.Location)
854 g.P("//\t*", fieldOneofType(field))
855 }
856 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
857 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
858}
859
860// genOneofTypes generates the interface type used for a oneof field,
861// and the wrapper types that satisfy that interface.
862//
863// It also generates the getter method for the parent oneof field
864// (but not the member fields).
865func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
866 ifName := oneofInterfaceName(oneof)
867 g.P("type ", ifName, " interface {")
868 g.P(ifName, "()")
869 g.P("}")
870 g.P()
871 for _, field := range oneof.Fields {
872 name := fieldOneofType(field)
873 g.Annotate(name.GoName, field.Location)
874 g.Annotate(name.GoName+"."+field.GoName, field.Location)
875 g.P("type ", name, " struct {")
876 goType, _ := fieldGoType(g, field)
877 tags := []string{
878 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
879 }
880 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
881 g.P("}")
882 g.P()
883 }
884 for _, field := range oneof.Fields {
885 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
886 g.P()
887 }
888 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
889 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
890 g.P("if m != nil {")
891 g.P("return m.", oneofFieldName(oneof))
892 g.P("}")
893 g.P("return nil")
894 g.P("}")
895 g.P()
896}
897
898// oneofFieldName returns the name of the struct field holding the oneof value.
899//
900// This function is trivial, but pulling out the name like this makes it easier
901// to experiment with alternative oneof implementations.
902func oneofFieldName(oneof *protogen.Oneof) string {
903 return oneof.GoName
904}
905
906// oneofInterfaceName returns the name of the interface type implemented by
907// the oneof field value types.
908func oneofInterfaceName(oneof *protogen.Oneof) string {
909 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
910}
911
912// genOneofWrappers generates the XXX_OneofWrappers method for a message.
913func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
914 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
915 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
916 g.P("return []interface{}{")
917 for _, oneof := range message.Oneofs {
918 for _, field := range oneof.Fields {
919 g.P("(*", fieldOneofType(field), ")(nil),")
920 }
921 }
922 g.P("}")
923 g.P("}")
924 g.P()
925}
926
927// fieldOneofType returns the wrapper type used to represent a field in a oneof.
928func fieldOneofType(field *protogen.Field) protogen.GoIdent {
929 ident := protogen.GoIdent{
930 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
931 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
932 }
933 // Check for collisions with nested messages or enums.
934 //
935 // This conflict resolution is incomplete: Among other things, it
936 // does not consider collisions with other oneof field types.
937 //
938 // TODO: Consider dropping this entirely. Detecting conflicts and
939 // producing an error is almost certainly better than permuting
940 // field and type names in mostly unpredictable ways.
941Loop:
942 for {
943 for _, message := range field.ParentMessage.Messages {
944 if message.GoIdent == ident {
945 ident.GoName += "_"
946 continue Loop
947 }
948 }
949 for _, enum := range field.ParentMessage.Enums {
950 if enum.GoIdent == ident {
951 ident.GoName += "_"
952 continue Loop
953 }
954 }
955 return ident
956 }
957}