blob: 4748f6773bd5cb365f9947aed15cc8bf4f43f304 [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 Neilce36f8d2018-09-13 15:19:08 -070014 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070015 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070016 "strings"
Damien Neil7bf3ce22018-12-21 15:54:06 -080017 "unicode"
18 "unicode/utf8"
Damien Neil7779e052018-09-07 14:14:06 -070019
20 "github.com/golang/protobuf/proto"
Joe Tsai05828db2018-11-01 13:52:16 -070021 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai01ab2962018-09-21 17:44:00 -070022 "github.com/golang/protobuf/v2/protogen"
23 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080024
25 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070026)
27
Damien Neild4127922018-09-12 11:13:49 -070028// generatedCodeVersion indicates a version of the generated code.
29// It is incremented whenever an incompatibility between the generated code and
30// proto package is introduced; the generated code references
31// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
Joe Tsaid7e97bc2018-11-26 12:57:27 -080032const generatedCodeVersion = 3
Damien Neild4127922018-09-12 11:13:49 -070033
Joe Tsaic1c17aa2018-11-16 11:14:14 -080034const (
Joe Tsai24ceb2b2018-12-04 22:53:56 -080035 mathPackage = protogen.GoImportPath("math")
36 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
37 protoapiPackage = protogen.GoImportPath("github.com/golang/protobuf/protoapi")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080038)
Damien Neil46abb572018-09-07 12:45:37 -070039
Damien Neild39efc82018-09-24 12:38:10 -070040type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070041 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080042
43 // vars containing the raw wire-encoded and compressed FileDescriptorProto.
44 descriptorRawVar string
45 descriptorGzipVar string
Joe Tsaib6405bd2018-11-15 14:44:37 -080046
Joe Tsai9667c482018-12-05 15:42:52 -080047 allEnums []*protogen.Enum
48 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
49 allMessages []*protogen.Message
50 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
51 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070052}
53
Joe Tsai24ceb2b2018-12-04 22:53:56 -080054// protoPackage returns the package to import, which is either the protoPackage
55// or the protoapiPackage constant.
56//
57// This special casing exists because we are unable to move InternalMessageInfo
58// to protoapi since the implementation behind that logic is heavy and
59// too intricately connected to other parts of the proto package.
60// The descriptor proto is special in that it avoids using InternalMessageInfo
61// so that it is able to depend solely on protoapi and break its dependency
62// on the proto package. It is still semantically correct for descriptor to
63// avoid using InternalMessageInfo, but it does incur some performance penalty.
64// This is acceptable for descriptor, which is a single proto file and is not
65// known to be in the hot path for any code.
66//
67// TODO: Remove this special-casing when the table-driven implementation has
68// been ported over to v2.
69func (f *fileInfo) protoPackage() protogen.GoImportPath {
70 if isDescriptor(f.File) {
71 return protoapiPackage
72 }
73 return protoPackage
74}
75
Damien Neil9c420a62018-09-27 15:26:33 -070076// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080077func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
78 filename := file.GeneratedFilenamePrefix + ".pb.go"
79 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070080 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070081 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070082 }
83
Damien Neil8012b442019-01-18 09:32:24 -080084 // Collect all enums, messages, and extensions in "flattened ordering".
85 // See fileinit.FileBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080086 f.allEnums = append(f.allEnums, f.Enums...)
87 f.allMessages = append(f.allMessages, f.Messages...)
88 f.allExtensions = append(f.allExtensions, f.Extensions...)
89 walkMessages(f.Messages, func(m *protogen.Message) {
90 f.allEnums = append(f.allEnums, m.Enums...)
91 f.allMessages = append(f.allMessages, m.Messages...)
92 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070093 })
Damien Neilce36f8d2018-09-13 15:19:08 -070094
Joe Tsai9667c482018-12-05 15:42:52 -080095 // Derive a reverse mapping of enum and message pointers to their index
96 // in allEnums and allMessages.
97 if len(f.allEnums) > 0 {
98 f.allEnumsByPtr = make(map[*protogen.Enum]int)
99 for i, e := range f.allEnums {
100 f.allEnumsByPtr[e] = i
101 }
102 }
103 if len(f.allMessages) > 0 {
104 f.allMessagesByPtr = make(map[*protogen.Message]int)
105 for i, m := range f.allMessages {
106 f.allMessagesByPtr[m] = i
107 }
108 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800109
Joe Tsai40692112019-02-27 20:25:51 -0800110 // Determine the name of the var holding the file descriptor.
111 f.descriptorRawVar = "xxx_" + f.GoDescriptorIdent.GoName + "_rawdesc"
Damien Neil8012b442019-01-18 09:32:24 -0800112 f.descriptorGzipVar = f.descriptorRawVar + "_gzipped"
Damien Neil46abb572018-09-07 12:45:37 -0700113
Damien Neil220c2022018-08-15 11:24:18 -0700114 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700115 if f.Proto.GetOptions().GetDeprecated() {
116 g.P("// ", f.Desc.Path(), " is a deprecated file.")
117 } else {
118 g.P("// source: ", f.Desc.Path())
119 }
Damien Neil220c2022018-08-15 11:24:18 -0700120 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -0700121 const filePackageField = 2 // FileDescriptorProto.package
Damien Neilba1159f2018-10-17 12:53:18 -0700122 g.PrintLeadingComments(protogen.Location{
123 SourceFile: f.Proto.GetName(),
124 Path: []int32{filePackageField},
125 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700126 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700127 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700128 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700129
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800130 if !isDescriptor(file) {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800131 g.P("// This is a compile-time assertion to ensure that this generated file")
132 g.P("// is compatible with the proto package it is being compiled against.")
133 g.P("// A compilation error at this line likely means your copy of the")
134 g.P("// proto package needs to be updated.")
135 g.P("const _ = ", protoPackage.Ident(fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion)),
136 "// please upgrade the proto package")
137 g.P()
138 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700139
Damien Neil73ac8852018-09-17 15:11:24 -0700140 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
141 genImport(gen, g, f, imps.Get(i))
142 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700143 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700144 genEnum(gen, g, f, enum)
145 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700146 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700147 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700148 }
Joe Tsai9667c482018-12-05 15:42:52 -0800149 for _, extension := range f.allExtensions {
Damien Neil993c04d2018-09-14 15:41:11 -0700150 genExtension(gen, g, f, extension)
151 }
Damien Neil220c2022018-08-15 11:24:18 -0700152
Damien Neilce36f8d2018-09-13 15:19:08 -0700153 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700154 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800155 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800156
157 return g
Damien Neil7779e052018-09-07 14:14:06 -0700158}
159
Damien Neil73ac8852018-09-17 15:11:24 -0700160// walkMessages calls f on each message and all of its descendants.
161func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
162 for _, m := range messages {
163 f(m)
164 walkMessages(m.Messages, f)
165 }
166}
167
Damien Neild39efc82018-09-24 12:38:10 -0700168func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700169 impFile, ok := gen.FileByName(imp.Path())
170 if !ok {
171 return
172 }
173 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700174 // Don't generate imports or aliases for types in the same Go package.
175 return
176 }
Damien Neil40a08052018-10-29 09:07:41 -0700177 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700178 // referenced, because other code and tools depend on having the
179 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700180 if !imp.IsWeak {
181 g.Import(impFile.GoImportPath)
182 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700183 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700184 return
185 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800186
187 // Generate public imports by generating the imported file, parsing it,
188 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800189 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800190 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800191 b, err := impGen.Content()
192 if err != nil {
193 gen.Error(err)
194 return
195 }
196 fset := token.NewFileSet()
197 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
198 if err != nil {
199 gen.Error(err)
200 return
201 }
Damien Neila7cbd062019-01-06 16:29:14 -0800202 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800203 // Don't import unexported symbols.
204 r, _ := utf8.DecodeRuneInString(name)
205 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700206 return
207 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800208 // Don't import the FileDescriptor.
209 if name == impFile.GoDescriptorIdent.GoName {
210 return
211 }
Damien Neila7cbd062019-01-06 16:29:14 -0800212 // Don't import decls referencing a symbol defined in another package.
213 // i.e., don't import decls which are themselves public imports:
214 //
215 // type T = somepackage.T
216 if _, ok := expr.(*ast.SelectorExpr); ok {
217 return
218 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800219 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
220 }
221 g.P("// Symbols defined in public import of ", imp.Path())
222 g.P()
223 for _, decl := range astFile.Decls {
224 switch decl := decl.(type) {
225 case *ast.GenDecl:
226 for _, spec := range decl.Specs {
227 switch spec := spec.(type) {
228 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800229 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800230 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800231 for i, name := range spec.Names {
232 var expr ast.Expr
233 if i < len(spec.Values) {
234 expr = spec.Values[i]
235 }
236 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800237 }
238 case *ast.ImportSpec:
239 default:
240 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800241 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700242 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700243 }
Damien Neil6b541312018-10-29 09:14:14 -0700244 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700245 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700246}
247
Damien Neild39efc82018-09-24 12:38:10 -0700248func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700249 // Trim the source_code_info from the descriptor.
250 // Marshal and gzip it.
Joe Tsaie1f8d502018-11-26 18:55:29 -0800251 descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto)
Damien Neil7779e052018-09-07 14:14:06 -0700252 descProto.SourceCodeInfo = nil
253 b, err := proto.Marshal(descProto)
254 if err != nil {
255 gen.Error(err)
256 return
257 }
Damien Neil7779e052018-09-07 14:14:06 -0700258
Damien Neil8012b442019-01-18 09:32:24 -0800259 g.P("var ", f.descriptorRawVar, " = []byte{")
260 g.P("// ", len(b), " bytes of the wire-encoded FileDescriptorProto")
Damien Neil7779e052018-09-07 14:14:06 -0700261 for len(b) > 0 {
262 n := 16
263 if n > len(b) {
264 n = len(b)
265 }
266
267 s := ""
268 for _, c := range b[:n] {
269 s += fmt.Sprintf("0x%02x,", c)
270 }
271 g.P(s)
272
273 b = b[n:]
274 }
275 g.P("}")
276 g.P()
Damien Neil8012b442019-01-18 09:32:24 -0800277
Joe Tsaicf81e672019-02-28 14:08:31 -0800278 // TODO: Modify CompressGZIP to lazy encode? Currently, the GZIP'd form
279 // is eagerly registered in v1, preventing any benefit from lazy encoding.
280 g.P("var ", f.descriptorGzipVar, " = ", protoapiPackage.Ident("CompressGZIP"), "(", f.descriptorRawVar, ")")
Damien Neil8012b442019-01-18 09:32:24 -0800281 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700282}
Damien Neilc7d07d92018-08-22 13:46:02 -0700283
Damien Neild39efc82018-09-24 12:38:10 -0700284func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700285 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700286 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700287 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800288 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700289 g.P("const (")
290 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700291 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700292 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700293 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800294 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700295 }
296 g.P(")")
297 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800298
299 // Generate support for protobuf reflection.
300 genReflectEnum(gen, g, f, enum)
301
Damien Neil46abb572018-09-07 12:45:37 -0700302 nameMap := enum.GoIdent.GoName + "_name"
303 g.P("var ", nameMap, " = map[int32]string{")
304 generated := make(map[protoreflect.EnumNumber]bool)
305 for _, value := range enum.Values {
306 duplicate := ""
307 if _, present := generated[value.Desc.Number()]; present {
308 duplicate = "// Duplicate value: "
309 }
310 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
311 generated[value.Desc.Number()] = true
312 }
313 g.P("}")
314 g.P()
315 valueMap := enum.GoIdent.GoName + "_value"
316 g.P("var ", valueMap, " = map[string]int32{")
317 for _, value := range enum.Values {
318 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
319 }
320 g.P("}")
321 g.P()
322 if enum.Desc.Syntax() != protoreflect.Proto3 {
323 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
324 g.P("p := new(", enum.GoIdent, ")")
325 g.P("*p = x")
326 g.P("return p")
327 g.P("}")
328 g.P()
329 }
330 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800331 g.P("return ", f.protoPackage().Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700332 g.P("}")
333 g.P()
334
Joe Tsai73903462018-12-14 12:22:41 -0800335 if enum.Desc.Syntax() == protoreflect.Proto2 {
Damien Neil46abb572018-09-07 12:45:37 -0700336 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800337 g.P("value, err := ", f.protoPackage().Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700338 g.P("if err != nil {")
339 g.P("return err")
340 g.P("}")
341 g.P("*x = ", enum.GoIdent, "(value)")
342 g.P("return nil")
343 g.P("}")
344 g.P()
345 }
346
347 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700348 for i := 1; i < len(enum.Location.Path); i += 2 {
349 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700350 }
351 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800352 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neil46abb572018-09-07 12:45:37 -0700353 g.P("}")
354 g.P()
355
Damien Neilea7baf42018-09-28 14:23:44 -0700356 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700357}
358
Damien Neil658051b2018-09-10 12:26:21 -0700359// enumRegistryName returns the name used to register an enum with the proto
360// package registry.
361//
362// Confusingly, this is <proto_package>.<go_ident>. This probably should have
363// been the full name of the proto enum type instead, but changing it at this
364// point would require thought.
365func enumRegistryName(enum *protogen.Enum) string {
366 // Find the FileDescriptor for this enum.
367 var desc protoreflect.Descriptor = enum.Desc
368 for {
369 p, ok := desc.Parent()
370 if !ok {
371 break
372 }
373 desc = p
374 }
375 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700376 if fdesc.Package() == "" {
377 return enum.GoIdent.GoName
378 }
Damien Neil658051b2018-09-10 12:26:21 -0700379 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
380}
381
Damien Neild39efc82018-09-24 12:38:10 -0700382func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700383 if message.Desc.IsMapEntry() {
384 return
385 }
386
Damien Neilba1159f2018-10-17 12:53:18 -0700387 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800388 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700389 if hasComment {
390 g.P("//")
391 }
392 g.P(deprecationComment(true))
393 }
Damien Neil162c1272018-10-04 12:42:37 -0700394 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700395 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700396 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700397 if field.OneofType != nil {
398 // It would be a bit simpler to iterate over the oneofs below,
399 // but generating the field here keeps the contents of the Go
400 // struct in the same order as the contents of the source
401 // .proto file.
402 if field == field.OneofType.Fields[0] {
403 genOneofField(gen, g, f, message, field.OneofType)
404 }
Damien Neil658051b2018-09-10 12:26:21 -0700405 continue
406 }
Damien Neilba1159f2018-10-17 12:53:18 -0700407 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700408 goType, pointer := fieldGoType(g, field)
409 if pointer {
410 goType = "*" + goType
411 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700412 tags := []string{
413 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
414 fmt.Sprintf("json:%q", fieldJSONTag(field)),
415 }
416 if field.Desc.IsMap() {
417 key := field.MessageType.Fields[0]
418 val := field.MessageType.Fields[1]
419 tags = append(tags,
420 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
421 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
422 )
423 }
Damien Neil162c1272018-10-04 12:42:37 -0700424 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700425 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800426 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700427 }
428 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700429
430 if message.Desc.ExtensionRanges().Len() > 0 {
431 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800432 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700433 tags = append(tags, `protobuf_messageset:"1"`)
434 }
435 tags = append(tags, `json:"-"`)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800436 g.P(f.protoPackage().Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700437 }
Damien Neil658051b2018-09-10 12:26:21 -0700438 g.P("XXX_unrecognized []byte `json:\"-\"`")
439 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700440 g.P("}")
441 g.P()
442
Joe Tsaib6405bd2018-11-15 14:44:37 -0800443 // Generate support for protobuf reflection.
444 genReflectMessage(gen, g, f, message)
445
Damien Neila1c6abc2018-09-12 13:36:34 -0700446 // Reset
447 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
448 // String
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800449 g.P("func (m *", message.GoIdent, ") String() string { return ", f.protoPackage().Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700450 // ProtoMessage
451 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
452 // Descriptor
453 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700454 for i := 1; i < len(message.Location.Path); i += 2 {
455 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700456 }
457 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800458 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neila1c6abc2018-09-12 13:36:34 -0700459 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700460 g.P()
461
462 // ExtensionRangeArray
463 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800464 protoExtRange := f.protoPackage().Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700465 extRangeVar := "extRange_" + message.GoIdent.GoName
466 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
467 for i := 0; i < extranges.Len(); i++ {
468 r := extranges.Get(i)
469 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
470 }
471 g.P("}")
472 g.P()
473 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
474 g.P("return ", extRangeVar)
475 g.P("}")
476 g.P()
477 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700478
Damien Neilea7baf42018-09-28 14:23:44 -0700479 genWellKnownType(g, "*", message.GoIdent, message.Desc)
480
Damien Neila1c6abc2018-09-12 13:36:34 -0700481 // Table-driven proto support.
482 //
483 // TODO: It does not scale to keep adding another method for every
484 // operation on protos that we want to switch over to using the
485 // table-driven approach. Instead, we should only add a single method
486 // that allows getting access to the *InternalMessageInfo struct and then
487 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800488 if !isDescriptor(f.File) {
489 // NOTE: We avoid adding table-driven support for descriptor proto
490 // since this depends on the v1 proto package, which would eventually
491 // need to depend on the descriptor itself.
492 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
493 // XXX_Unmarshal
494 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
495 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
496 g.P("}")
497 // XXX_Marshal
498 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
499 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
500 g.P("}")
501 // XXX_Merge
502 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
503 g.P(messageInfoVar, ".Merge(m, src)")
504 g.P("}")
505 // XXX_Size
506 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
507 g.P("return ", messageInfoVar, ".Size(m)")
508 g.P("}")
509 // XXX_DiscardUnknown
510 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
511 g.P(messageInfoVar, ".DiscardUnknown(m)")
512 g.P("}")
513 g.P()
514 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
515 g.P()
516 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700517
Damien Neilebc699d2018-09-13 08:50:13 -0700518 // Constants and vars holding the default values of fields.
519 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800520 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700521 continue
522 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700523 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700524 def := field.Desc.Default()
525 switch field.Desc.Kind() {
526 case protoreflect.StringKind:
527 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
528 case protoreflect.BytesKind:
529 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
530 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700531 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700532 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700533 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700534 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
535 case protoreflect.FloatKind, protoreflect.DoubleKind:
536 // Floating point numbers need extra handling for -Inf/Inf/NaN.
537 f := field.Desc.Default().Float()
538 goType := "float64"
539 if field.Desc.Kind() == protoreflect.FloatKind {
540 goType = "float32"
541 }
542 // funcCall returns a call to a function in the math package,
543 // possibly converting the result to float32.
544 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800545 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700546 if goType != "float64" {
547 s = goType + "(" + s + ")"
548 }
549 return s
550 }
551 switch {
552 case math.IsInf(f, -1):
553 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
554 case math.IsInf(f, 1):
555 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
556 case math.IsNaN(f):
557 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
558 default:
Damien Neil982684b2018-09-28 14:12:41 -0700559 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700560 }
561 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700562 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700563 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
564 }
565 }
566 g.P()
567
Damien Neil77f82fe2018-09-13 10:59:17 -0700568 // Getters.
569 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700570 if field.OneofType != nil {
571 if field == field.OneofType.Fields[0] {
572 genOneofTypes(gen, g, f, message, field.OneofType)
573 }
574 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700575 goType, pointer := fieldGoType(g, field)
576 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800577 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700578 g.P(deprecationComment(true))
579 }
Damien Neil162c1272018-10-04 12:42:37 -0700580 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700581 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
582 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700583 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700584 g.P("return x.", field.GoName)
585 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700586 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700587 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
588 g.P("if m != nil {")
589 } else {
590 g.P("if m != nil && m.", field.GoName, " != nil {")
591 }
592 star := ""
593 if pointer {
594 star = "*"
595 }
596 g.P("return ", star, " m.", field.GoName)
597 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700598 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700599 g.P("return ", defaultValue)
600 g.P("}")
601 g.P()
602 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700603
Damien Neil1fa78d82018-09-13 13:12:36 -0700604 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800605 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700606 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700607}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700608
Damien Neil77f82fe2018-09-13 10:59:17 -0700609// fieldGoType returns the Go type used for a field.
610//
611// If it returns pointer=true, the struct field is a pointer to the type.
612func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700613 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700614 switch field.Desc.Kind() {
615 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700617 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700619 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700620 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700621 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700623 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700625 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700626 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700627 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700629 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700631 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700632 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700633 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700634 goType = "[]byte"
635 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700636 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700637 if field.Desc.IsMap() {
638 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
639 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
640 return fmt.Sprintf("map[%v]%v", keyType, valType), false
641 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700642 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
643 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700644 }
645 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700646 goType = "[]" + goType
647 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700648 }
Damien Neil44000a12018-10-24 12:31:16 -0700649 // Extension fields always have pointer type, even when defined in a proto3 file.
650 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700651 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700652 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700653 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700654}
655
656func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700657 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700658 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700659 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700660 }
Joe Tsai05828db2018-11-01 13:52:16 -0700661 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700662}
663
Damien Neil77f82fe2018-09-13 10:59:17 -0700664func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
665 if field.Desc.Cardinality() == protoreflect.Repeated {
666 return "nil"
667 }
Joe Tsai9667c482018-12-05 15:42:52 -0800668 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700669 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700670 if field.Desc.Kind() == protoreflect.BytesKind {
671 return "append([]byte(nil), " + defVarName + "...)"
672 }
673 return defVarName
674 }
675 switch field.Desc.Kind() {
676 case protoreflect.BoolKind:
677 return "false"
678 case protoreflect.StringKind:
679 return `""`
680 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
681 return "nil"
682 case protoreflect.EnumKind:
683 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
684 default:
685 return "0"
686 }
687}
688
Damien Neil658051b2018-09-10 12:26:21 -0700689func fieldJSONTag(field *protogen.Field) string {
690 return string(field.Desc.Name()) + ",omitempty"
691}
692
Damien Neild39efc82018-09-24 12:38:10 -0700693func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700694 // Special case for proto2 message sets: If this extension is extending
695 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
696 // then drop that last component.
697 //
698 // TODO: This should be implemented in the text formatter rather than the generator.
699 // In addition, the situation for when to apply this special case is implemented
700 // differently in other languages:
701 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
702 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700703 if n, ok := isExtensionMessageSetElement(extension); ok {
704 name = n
Damien Neil154da982018-09-19 13:21:58 -0700705 }
706
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800707 g.P("var ", extensionVar(f.File, extension), " = &", f.protoPackage().Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700708 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
709 goType, pointer := fieldGoType(g, extension)
710 if pointer {
711 goType = "*" + goType
712 }
713 g.P("ExtensionType: (", goType, ")(nil),")
714 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700715 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700716 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
717 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
718 g.P("}")
719 g.P()
720}
721
Damien Neil62386962018-10-30 10:35:48 -0700722// isExtensionMessageSetELement returns the adjusted name of an extension
723// which extends proto2.bridge.MessageSet.
724func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800725 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700726 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
727 return "", false
728 }
729 if extension.ParentMessage == nil {
730 // This case shouldn't be given special handling at all--we're
731 // only supposed to drop the ".message_set_extension" for
732 // extensions defined within a message (i.e., the extension
733 // takes the message's name).
734 //
735 // This matches the behavior of the v1 generator, however.
736 //
737 // TODO: See if we can drop this case.
738 name = extension.Desc.FullName()
739 name = name[:len(name)-len("message_set_extension")]
740 return name, true
741 }
742 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700743}
744
Damien Neil993c04d2018-09-14 15:41:11 -0700745// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700746func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700747 name := "E_"
748 if extension.ParentMessage != nil {
749 name += extension.ParentMessage.GoIdent.GoName + "_"
750 }
751 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800752 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700753}
754
Damien Neilce36f8d2018-09-13 15:19:08 -0700755// genInitFunction generates an init function that registers the types in the
756// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700757func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neilce36f8d2018-09-13 15:19:08 -0700758 g.P("func init() {")
Damien Neil8012b442019-01-18 09:32:24 -0800759 g.P(f.protoPackage().Ident("RegisterFile"), "(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorGzipVar, ")")
Damien Neil154da982018-09-19 13:21:58 -0700760 for _, enum := range f.allEnums {
761 name := enum.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800762 g.P(f.protoPackage().Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700763 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700764 for _, message := range f.allMessages {
765 if message.Desc.IsMapEntry() {
766 continue
767 }
768
769 name := message.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800770 g.P(f.protoPackage().Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700771
772 // Types of map fields, sorted by the name of the field message type.
773 var mapFields []*protogen.Field
774 for _, field := range message.Fields {
775 if field.Desc.IsMap() {
776 mapFields = append(mapFields, field)
777 }
778 }
779 sort.Slice(mapFields, func(i, j int) bool {
780 ni := mapFields[i].MessageType.Desc.FullName()
781 nj := mapFields[j].MessageType.Desc.FullName()
782 return ni < nj
783 })
784 for _, field := range mapFields {
785 typeName := string(field.MessageType.Desc.FullName())
786 goType, _ := fieldGoType(g, field)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800787 g.P(f.protoPackage().Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700788 }
789 }
Joe Tsai9667c482018-12-05 15:42:52 -0800790 for _, extension := range f.allExtensions {
791 g.P(f.protoPackage().Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil993c04d2018-09-14 15:41:11 -0700792 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700793 g.P("}")
794 g.P()
795}
796
Damien Neil55fe1c02018-09-17 15:11:24 -0700797// deprecationComment returns a standard deprecation comment if deprecated is true.
798func deprecationComment(deprecated bool) string {
799 if !deprecated {
800 return ""
801 }
802 return "// Deprecated: Do not use."
803}
804
Damien Neilea7baf42018-09-28 14:23:44 -0700805func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700806 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700807 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700808 g.P()
809 }
810}
811
812// Names of messages and enums for which we will generate XXX_WellKnownType methods.
813var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700814 "google.protobuf.Any": true,
815 "google.protobuf.Duration": true,
816 "google.protobuf.Empty": true,
817 "google.protobuf.Struct": true,
818 "google.protobuf.Timestamp": true,
819
820 "google.protobuf.BoolValue": true,
821 "google.protobuf.BytesValue": true,
822 "google.protobuf.DoubleValue": true,
823 "google.protobuf.FloatValue": true,
824 "google.protobuf.Int32Value": true,
825 "google.protobuf.Int64Value": true,
826 "google.protobuf.ListValue": true,
827 "google.protobuf.NullValue": true,
828 "google.protobuf.StringValue": true,
829 "google.protobuf.UInt32Value": true,
830 "google.protobuf.UInt64Value": true,
831 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700832}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800833
834// genOneofField generates the struct field for a oneof.
835func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
836 if g.PrintLeadingComments(oneof.Location) {
837 g.P("//")
838 }
839 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
840 for _, field := range oneof.Fields {
841 g.PrintLeadingComments(field.Location)
842 g.P("//\t*", fieldOneofType(field))
843 }
844 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
845 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
846}
847
848// genOneofTypes generates the interface type used for a oneof field,
849// and the wrapper types that satisfy that interface.
850//
851// It also generates the getter method for the parent oneof field
852// (but not the member fields).
853func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
854 ifName := oneofInterfaceName(oneof)
855 g.P("type ", ifName, " interface {")
856 g.P(ifName, "()")
857 g.P("}")
858 g.P()
859 for _, field := range oneof.Fields {
860 name := fieldOneofType(field)
861 g.Annotate(name.GoName, field.Location)
862 g.Annotate(name.GoName+"."+field.GoName, field.Location)
863 g.P("type ", name, " struct {")
864 goType, _ := fieldGoType(g, field)
865 tags := []string{
866 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
867 }
868 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
869 g.P("}")
870 g.P()
871 }
872 for _, field := range oneof.Fields {
873 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
874 g.P()
875 }
876 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
877 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
878 g.P("if m != nil {")
879 g.P("return m.", oneofFieldName(oneof))
880 g.P("}")
881 g.P("return nil")
882 g.P("}")
883 g.P()
884}
885
886// oneofFieldName returns the name of the struct field holding the oneof value.
887//
888// This function is trivial, but pulling out the name like this makes it easier
889// to experiment with alternative oneof implementations.
890func oneofFieldName(oneof *protogen.Oneof) string {
891 return oneof.GoName
892}
893
894// oneofInterfaceName returns the name of the interface type implemented by
895// the oneof field value types.
896func oneofInterfaceName(oneof *protogen.Oneof) string {
897 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
898}
899
900// genOneofWrappers generates the XXX_OneofWrappers method for a message.
901func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
902 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
903 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
904 g.P("return []interface{}{")
905 for _, oneof := range message.Oneofs {
906 for _, field := range oneof.Fields {
907 g.P("(*", fieldOneofType(field), ")(nil),")
908 }
909 }
910 g.P("}")
911 g.P("}")
912 g.P()
913}
914
915// fieldOneofType returns the wrapper type used to represent a field in a oneof.
916func fieldOneofType(field *protogen.Field) protogen.GoIdent {
917 ident := protogen.GoIdent{
918 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
919 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
920 }
921 // Check for collisions with nested messages or enums.
922 //
923 // This conflict resolution is incomplete: Among other things, it
924 // does not consider collisions with other oneof field types.
925 //
926 // TODO: Consider dropping this entirely. Detecting conflicts and
927 // producing an error is almost certainly better than permuting
928 // field and type names in mostly unpredictable ways.
929Loop:
930 for {
931 for _, message := range field.ParentMessage.Messages {
932 if message.GoIdent == ident {
933 ident.GoName += "_"
934 continue Loop
935 }
936 }
937 for _, enum := range field.ParentMessage.Enums {
938 if enum.GoIdent == ident {
939 ident.GoName += "_"
940 continue Loop
941 }
942 }
943 return ident
944 }
945}