blob: 46d26a246934f8c7352d8071900a6b99ad6bc270 [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 "bytes"
10 "compress/gzip"
11 "crypto/sha256"
12 "encoding/hex"
13 "fmt"
Damien Neil7bf3ce22018-12-21 15:54:06 -080014 "go/ast"
15 "go/parser"
16 "go/token"
Damien Neilebc699d2018-09-13 08:50:13 -070017 "math"
Damien Neilce36f8d2018-09-13 15:19:08 -070018 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070019 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070020 "strings"
Damien Neil7bf3ce22018-12-21 15:54:06 -080021 "unicode"
22 "unicode/utf8"
Damien Neil7779e052018-09-07 14:14:06 -070023
24 "github.com/golang/protobuf/proto"
Joe Tsai05828db2018-11-01 13:52:16 -070025 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai01ab2962018-09-21 17:44:00 -070026 "github.com/golang/protobuf/v2/protogen"
27 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080028
29 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070030)
31
Damien Neild4127922018-09-12 11:13:49 -070032// generatedCodeVersion indicates a version of the generated code.
33// It is incremented whenever an incompatibility between the generated code and
34// proto package is introduced; the generated code references
35// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
Joe Tsaid7e97bc2018-11-26 12:57:27 -080036const generatedCodeVersion = 3
Damien Neild4127922018-09-12 11:13:49 -070037
Joe Tsaic1c17aa2018-11-16 11:14:14 -080038const (
Joe Tsai24ceb2b2018-12-04 22:53:56 -080039 fmtPackage = protogen.GoImportPath("fmt")
40 mathPackage = protogen.GoImportPath("math")
41 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
42 protoapiPackage = protogen.GoImportPath("github.com/golang/protobuf/protoapi")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080043)
Damien Neil46abb572018-09-07 12:45:37 -070044
Damien Neild39efc82018-09-24 12:38:10 -070045type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070046 *protogen.File
Damien Neil46abb572018-09-07 12:45:37 -070047 descriptorVar string // var containing the gzipped FileDescriptorProto
Joe Tsaib6405bd2018-11-15 14:44:37 -080048
Joe Tsai9667c482018-12-05 15:42:52 -080049 allEnums []*protogen.Enum
50 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
51 allMessages []*protogen.Message
52 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
53 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070054}
55
Joe Tsai24ceb2b2018-12-04 22:53:56 -080056// protoPackage returns the package to import, which is either the protoPackage
57// or the protoapiPackage constant.
58//
59// This special casing exists because we are unable to move InternalMessageInfo
60// to protoapi since the implementation behind that logic is heavy and
61// too intricately connected to other parts of the proto package.
62// The descriptor proto is special in that it avoids using InternalMessageInfo
63// so that it is able to depend solely on protoapi and break its dependency
64// on the proto package. It is still semantically correct for descriptor to
65// avoid using InternalMessageInfo, but it does incur some performance penalty.
66// This is acceptable for descriptor, which is a single proto file and is not
67// known to be in the hot path for any code.
68//
69// TODO: Remove this special-casing when the table-driven implementation has
70// been ported over to v2.
71func (f *fileInfo) protoPackage() protogen.GoImportPath {
72 if isDescriptor(f.File) {
73 return protoapiPackage
74 }
75 return protoPackage
76}
77
Damien Neil9c420a62018-09-27 15:26:33 -070078// GenerateFile generates the contents of a .pb.go file.
79func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
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
Joe Tsai9667c482018-12-05 15:42:52 -080084 // Collect all enums, messages, and extensions in a breadth-first order.
85 f.allEnums = append(f.allEnums, f.Enums...)
86 f.allMessages = append(f.allMessages, f.Messages...)
87 f.allExtensions = append(f.allExtensions, f.Extensions...)
88 walkMessages(f.Messages, func(m *protogen.Message) {
89 f.allEnums = append(f.allEnums, m.Enums...)
90 f.allMessages = append(f.allMessages, m.Messages...)
91 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070092 })
Damien Neilce36f8d2018-09-13 15:19:08 -070093
Joe Tsai9667c482018-12-05 15:42:52 -080094 // Derive a reverse mapping of enum and message pointers to their index
95 // in allEnums and allMessages.
96 if len(f.allEnums) > 0 {
97 f.allEnumsByPtr = make(map[*protogen.Enum]int)
98 for i, e := range f.allEnums {
99 f.allEnumsByPtr[e] = i
100 }
101 }
102 if len(f.allMessages) > 0 {
103 f.allMessagesByPtr = make(map[*protogen.Message]int)
104 for i, m := range f.allMessages {
105 f.allMessagesByPtr[m] = i
106 }
107 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800108
Damien Neil46abb572018-09-07 12:45:37 -0700109 // Determine the name of the var holding the file descriptor:
110 //
111 // fileDescriptor_<hash of filename>
112 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
113 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
114
Damien Neil220c2022018-08-15 11:24:18 -0700115 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700116 if f.Proto.GetOptions().GetDeprecated() {
117 g.P("// ", f.Desc.Path(), " is a deprecated file.")
118 } else {
119 g.P("// source: ", f.Desc.Path())
120 }
Damien Neil220c2022018-08-15 11:24:18 -0700121 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -0700122 const filePackageField = 2 // FileDescriptorProto.package
Damien Neilba1159f2018-10-17 12:53:18 -0700123 g.PrintLeadingComments(protogen.Location{
124 SourceFile: f.Proto.GetName(),
125 Path: []int32{filePackageField},
126 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700127 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700128 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700129 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700130
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800131 if !isDescriptor(file) {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800132 g.P("// This is a compile-time assertion to ensure that this generated file")
133 g.P("// is compatible with the proto package it is being compiled against.")
134 g.P("// A compilation error at this line likely means your copy of the")
135 g.P("// proto package needs to be updated.")
136 g.P("const _ = ", protoPackage.Ident(fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion)),
137 "// please upgrade the proto package")
138 g.P()
139 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700140
Damien Neil73ac8852018-09-17 15:11:24 -0700141 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
142 genImport(gen, g, f, imps.Get(i))
143 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700144 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700145 genEnum(gen, g, f, enum)
146 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700147 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700148 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700149 }
Joe Tsai9667c482018-12-05 15:42:52 -0800150 for _, extension := range f.allExtensions {
Damien Neil993c04d2018-09-14 15:41:11 -0700151 genExtension(gen, g, f, extension)
152 }
Damien Neil220c2022018-08-15 11:24:18 -0700153
Damien Neilce36f8d2018-09-13 15:19:08 -0700154 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700155 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800156 genReflectInitFunction(gen, g, f)
157 genReflectFileDescriptor(gen, g, f)
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.
189 impGen := gen.NewGeneratedFile("temp.go", impFile.GoImportPath)
190 impGen.Skip()
191 GenerateFile(gen, impFile, impGen)
192 b, err := impGen.Content()
193 if err != nil {
194 gen.Error(err)
195 return
196 }
197 fset := token.NewFileSet()
198 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
199 if err != nil {
200 gen.Error(err)
201 return
202 }
Damien Neila7cbd062019-01-06 16:29:14 -0800203 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800204 // Don't import unexported symbols.
205 r, _ := utf8.DecodeRuneInString(name)
206 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700207 return
208 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800209 // Don't import the FileDescriptor.
210 if name == impFile.GoDescriptorIdent.GoName {
211 return
212 }
Damien Neila7cbd062019-01-06 16:29:14 -0800213 // Don't import decls referencing a symbol defined in another package.
214 // i.e., don't import decls which are themselves public imports:
215 //
216 // type T = somepackage.T
217 if _, ok := expr.(*ast.SelectorExpr); ok {
218 return
219 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800220 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
221 }
222 g.P("// Symbols defined in public import of ", imp.Path())
223 g.P()
224 for _, decl := range astFile.Decls {
225 switch decl := decl.(type) {
226 case *ast.GenDecl:
227 for _, spec := range decl.Specs {
228 switch spec := spec.(type) {
229 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800230 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800231 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800232 for i, name := range spec.Names {
233 var expr ast.Expr
234 if i < len(spec.Values) {
235 expr = spec.Values[i]
236 }
237 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800238 }
239 case *ast.ImportSpec:
240 default:
241 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800242 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700243 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700244 }
Damien Neil6b541312018-10-29 09:14:14 -0700245 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700246 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700247}
248
Damien Neild39efc82018-09-24 12:38:10 -0700249func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700250 // Trim the source_code_info from the descriptor.
251 // Marshal and gzip it.
Joe Tsaie1f8d502018-11-26 18:55:29 -0800252 descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto)
Damien Neil7779e052018-09-07 14:14:06 -0700253 descProto.SourceCodeInfo = nil
254 b, err := proto.Marshal(descProto)
255 if err != nil {
256 gen.Error(err)
257 return
258 }
259 var buf bytes.Buffer
260 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
261 w.Write(b)
262 w.Close()
263 b = buf.Bytes()
264
Damien Neil46abb572018-09-07 12:45:37 -0700265 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700266 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
267 for len(b) > 0 {
268 n := 16
269 if n > len(b) {
270 n = len(b)
271 }
272
273 s := ""
274 for _, c := range b[:n] {
275 s += fmt.Sprintf("0x%02x,", c)
276 }
277 g.P(s)
278
279 b = b[n:]
280 }
281 g.P("}")
282 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700283}
Damien Neilc7d07d92018-08-22 13:46:02 -0700284
Damien Neild39efc82018-09-24 12:38:10 -0700285func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700286 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700287 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700288 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800289 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700290 g.P("const (")
291 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700292 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700293 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700294 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800295 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700296 }
297 g.P(")")
298 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800299
300 // Generate support for protobuf reflection.
301 genReflectEnum(gen, g, f, enum)
302
Damien Neil46abb572018-09-07 12:45:37 -0700303 nameMap := enum.GoIdent.GoName + "_name"
304 g.P("var ", nameMap, " = map[int32]string{")
305 generated := make(map[protoreflect.EnumNumber]bool)
306 for _, value := range enum.Values {
307 duplicate := ""
308 if _, present := generated[value.Desc.Number()]; present {
309 duplicate = "// Duplicate value: "
310 }
311 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
312 generated[value.Desc.Number()] = true
313 }
314 g.P("}")
315 g.P()
316 valueMap := enum.GoIdent.GoName + "_value"
317 g.P("var ", valueMap, " = map[string]int32{")
318 for _, value := range enum.Values {
319 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
320 }
321 g.P("}")
322 g.P()
323 if enum.Desc.Syntax() != protoreflect.Proto3 {
324 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
325 g.P("p := new(", enum.GoIdent, ")")
326 g.P("*p = x")
327 g.P("return p")
328 g.P("}")
329 g.P()
330 }
331 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800332 g.P("return ", f.protoPackage().Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700333 g.P("}")
334 g.P()
335
Joe Tsai73903462018-12-14 12:22:41 -0800336 if enum.Desc.Syntax() == protoreflect.Proto2 {
Damien Neil46abb572018-09-07 12:45:37 -0700337 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800338 g.P("value, err := ", f.protoPackage().Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700339 g.P("if err != nil {")
340 g.P("return err")
341 g.P("}")
342 g.P("*x = ", enum.GoIdent, "(value)")
343 g.P("return nil")
344 g.P("}")
345 g.P()
346 }
347
348 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700349 for i := 1; i < len(enum.Location.Path); i += 2 {
350 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700351 }
352 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
353 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
354 g.P("}")
355 g.P()
356
Damien Neilea7baf42018-09-28 14:23:44 -0700357 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700358}
359
Damien Neil658051b2018-09-10 12:26:21 -0700360// enumRegistryName returns the name used to register an enum with the proto
361// package registry.
362//
363// Confusingly, this is <proto_package>.<go_ident>. This probably should have
364// been the full name of the proto enum type instead, but changing it at this
365// point would require thought.
366func enumRegistryName(enum *protogen.Enum) string {
367 // Find the FileDescriptor for this enum.
368 var desc protoreflect.Descriptor = enum.Desc
369 for {
370 p, ok := desc.Parent()
371 if !ok {
372 break
373 }
374 desc = p
375 }
376 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700377 if fdesc.Package() == "" {
378 return enum.GoIdent.GoName
379 }
Damien Neil658051b2018-09-10 12:26:21 -0700380 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
381}
382
Damien Neild39efc82018-09-24 12:38:10 -0700383func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700384 if message.Desc.IsMapEntry() {
385 return
386 }
387
Damien Neilba1159f2018-10-17 12:53:18 -0700388 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800389 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700390 if hasComment {
391 g.P("//")
392 }
393 g.P(deprecationComment(true))
394 }
Damien Neil162c1272018-10-04 12:42:37 -0700395 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700396 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700397 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700398 if field.OneofType != nil {
399 // It would be a bit simpler to iterate over the oneofs below,
400 // but generating the field here keeps the contents of the Go
401 // struct in the same order as the contents of the source
402 // .proto file.
403 if field == field.OneofType.Fields[0] {
404 genOneofField(gen, g, f, message, field.OneofType)
405 }
Damien Neil658051b2018-09-10 12:26:21 -0700406 continue
407 }
Damien Neilba1159f2018-10-17 12:53:18 -0700408 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700409 goType, pointer := fieldGoType(g, field)
410 if pointer {
411 goType = "*" + goType
412 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700413 tags := []string{
414 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
415 fmt.Sprintf("json:%q", fieldJSONTag(field)),
416 }
417 if field.Desc.IsMap() {
418 key := field.MessageType.Fields[0]
419 val := field.MessageType.Fields[1]
420 tags = append(tags,
421 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
422 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
423 )
424 }
Damien Neil162c1272018-10-04 12:42:37 -0700425 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700426 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800427 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700428 }
429 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700430
431 if message.Desc.ExtensionRanges().Len() > 0 {
432 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800433 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700434 tags = append(tags, `protobuf_messageset:"1"`)
435 }
436 tags = append(tags, `json:"-"`)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800437 g.P(f.protoPackage().Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700438 }
Damien Neil658051b2018-09-10 12:26:21 -0700439 g.P("XXX_unrecognized []byte `json:\"-\"`")
440 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700441 g.P("}")
442 g.P()
443
Joe Tsaib6405bd2018-11-15 14:44:37 -0800444 // Generate support for protobuf reflection.
445 genReflectMessage(gen, g, f, message)
446
Damien Neila1c6abc2018-09-12 13:36:34 -0700447 // Reset
448 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
449 // String
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800450 g.P("func (m *", message.GoIdent, ") String() string { return ", f.protoPackage().Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700451 // ProtoMessage
452 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
453 // Descriptor
454 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700455 for i := 1; i < len(message.Location.Path); i += 2 {
456 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700457 }
458 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
459 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
460 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700461 g.P()
462
463 // ExtensionRangeArray
464 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800465 protoExtRange := f.protoPackage().Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700466 extRangeVar := "extRange_" + message.GoIdent.GoName
467 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
468 for i := 0; i < extranges.Len(); i++ {
469 r := extranges.Get(i)
470 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
471 }
472 g.P("}")
473 g.P()
474 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
475 g.P("return ", extRangeVar)
476 g.P("}")
477 g.P()
478 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700479
Damien Neilea7baf42018-09-28 14:23:44 -0700480 genWellKnownType(g, "*", message.GoIdent, message.Desc)
481
Damien Neila1c6abc2018-09-12 13:36:34 -0700482 // Table-driven proto support.
483 //
484 // TODO: It does not scale to keep adding another method for every
485 // operation on protos that we want to switch over to using the
486 // table-driven approach. Instead, we should only add a single method
487 // that allows getting access to the *InternalMessageInfo struct and then
488 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800489 if !isDescriptor(f.File) {
490 // NOTE: We avoid adding table-driven support for descriptor proto
491 // since this depends on the v1 proto package, which would eventually
492 // need to depend on the descriptor itself.
493 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
494 // XXX_Unmarshal
495 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
496 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
497 g.P("}")
498 // XXX_Marshal
499 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
500 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
501 g.P("}")
502 // XXX_Merge
503 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
504 g.P(messageInfoVar, ".Merge(m, src)")
505 g.P("}")
506 // XXX_Size
507 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
508 g.P("return ", messageInfoVar, ".Size(m)")
509 g.P("}")
510 // XXX_DiscardUnknown
511 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
512 g.P(messageInfoVar, ".DiscardUnknown(m)")
513 g.P("}")
514 g.P()
515 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
516 g.P()
517 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700518
Damien Neilebc699d2018-09-13 08:50:13 -0700519 // Constants and vars holding the default values of fields.
520 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800521 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700522 continue
523 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700524 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700525 def := field.Desc.Default()
526 switch field.Desc.Kind() {
527 case protoreflect.StringKind:
528 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
529 case protoreflect.BytesKind:
530 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
531 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700532 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700533 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700534 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700535 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
536 case protoreflect.FloatKind, protoreflect.DoubleKind:
537 // Floating point numbers need extra handling for -Inf/Inf/NaN.
538 f := field.Desc.Default().Float()
539 goType := "float64"
540 if field.Desc.Kind() == protoreflect.FloatKind {
541 goType = "float32"
542 }
543 // funcCall returns a call to a function in the math package,
544 // possibly converting the result to float32.
545 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800546 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700547 if goType != "float64" {
548 s = goType + "(" + s + ")"
549 }
550 return s
551 }
552 switch {
553 case math.IsInf(f, -1):
554 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
555 case math.IsInf(f, 1):
556 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
557 case math.IsNaN(f):
558 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
559 default:
Damien Neil982684b2018-09-28 14:12:41 -0700560 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700561 }
562 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700563 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700564 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
565 }
566 }
567 g.P()
568
Damien Neil77f82fe2018-09-13 10:59:17 -0700569 // Getters.
570 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700571 if field.OneofType != nil {
572 if field == field.OneofType.Fields[0] {
573 genOneofTypes(gen, g, f, message, field.OneofType)
574 }
575 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700576 goType, pointer := fieldGoType(g, field)
577 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800578 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700579 g.P(deprecationComment(true))
580 }
Damien Neil162c1272018-10-04 12:42:37 -0700581 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700582 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
583 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700584 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700585 g.P("return x.", field.GoName)
586 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700587 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700588 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
589 g.P("if m != nil {")
590 } else {
591 g.P("if m != nil && m.", field.GoName, " != nil {")
592 }
593 star := ""
594 if pointer {
595 star = "*"
596 }
597 g.P("return ", star, " m.", field.GoName)
598 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700599 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700600 g.P("return ", defaultValue)
601 g.P("}")
602 g.P()
603 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700604
Damien Neil1fa78d82018-09-13 13:12:36 -0700605 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800606 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700607 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700608}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700609
Damien Neil77f82fe2018-09-13 10:59:17 -0700610// fieldGoType returns the Go type used for a field.
611//
612// If it returns pointer=true, the struct field is a pointer to the type.
613func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700615 switch field.Desc.Kind() {
616 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700617 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700618 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700619 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700620 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700621 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700622 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700623 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700624 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700625 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700626 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700627 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700628 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700629 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700630 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700631 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700632 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700633 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700634 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700635 goType = "[]byte"
636 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700637 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700638 if field.Desc.IsMap() {
639 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
640 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
641 return fmt.Sprintf("map[%v]%v", keyType, valType), false
642 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700643 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
644 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700645 }
646 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700647 goType = "[]" + goType
648 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700649 }
Damien Neil44000a12018-10-24 12:31:16 -0700650 // Extension fields always have pointer type, even when defined in a proto3 file.
651 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700652 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700653 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700654 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700655}
656
657func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700658 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700659 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700660 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700661 }
Joe Tsai05828db2018-11-01 13:52:16 -0700662 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700663}
664
Damien Neil77f82fe2018-09-13 10:59:17 -0700665func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
666 if field.Desc.Cardinality() == protoreflect.Repeated {
667 return "nil"
668 }
Joe Tsai9667c482018-12-05 15:42:52 -0800669 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700670 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700671 if field.Desc.Kind() == protoreflect.BytesKind {
672 return "append([]byte(nil), " + defVarName + "...)"
673 }
674 return defVarName
675 }
676 switch field.Desc.Kind() {
677 case protoreflect.BoolKind:
678 return "false"
679 case protoreflect.StringKind:
680 return `""`
681 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
682 return "nil"
683 case protoreflect.EnumKind:
684 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
685 default:
686 return "0"
687 }
688}
689
Damien Neil658051b2018-09-10 12:26:21 -0700690func fieldJSONTag(field *protogen.Field) string {
691 return string(field.Desc.Name()) + ",omitempty"
692}
693
Damien Neild39efc82018-09-24 12:38:10 -0700694func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700695 // Special case for proto2 message sets: If this extension is extending
696 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
697 // then drop that last component.
698 //
699 // TODO: This should be implemented in the text formatter rather than the generator.
700 // In addition, the situation for when to apply this special case is implemented
701 // differently in other languages:
702 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
703 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700704 if n, ok := isExtensionMessageSetElement(extension); ok {
705 name = n
Damien Neil154da982018-09-19 13:21:58 -0700706 }
707
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800708 g.P("var ", extensionVar(f.File, extension), " = &", f.protoPackage().Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700709 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
710 goType, pointer := fieldGoType(g, extension)
711 if pointer {
712 goType = "*" + goType
713 }
714 g.P("ExtensionType: (", goType, ")(nil),")
715 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700716 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700717 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
718 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
719 g.P("}")
720 g.P()
721}
722
Damien Neil62386962018-10-30 10:35:48 -0700723// isExtensionMessageSetELement returns the adjusted name of an extension
724// which extends proto2.bridge.MessageSet.
725func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800726 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700727 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
728 return "", false
729 }
730 if extension.ParentMessage == nil {
731 // This case shouldn't be given special handling at all--we're
732 // only supposed to drop the ".message_set_extension" for
733 // extensions defined within a message (i.e., the extension
734 // takes the message's name).
735 //
736 // This matches the behavior of the v1 generator, however.
737 //
738 // TODO: See if we can drop this case.
739 name = extension.Desc.FullName()
740 name = name[:len(name)-len("message_set_extension")]
741 return name, true
742 }
743 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700744}
745
Damien Neil993c04d2018-09-14 15:41:11 -0700746// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700747func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700748 name := "E_"
749 if extension.ParentMessage != nil {
750 name += extension.ParentMessage.GoIdent.GoName + "_"
751 }
752 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800753 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700754}
755
Damien Neilce36f8d2018-09-13 15:19:08 -0700756// genInitFunction generates an init function that registers the types in the
757// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700758func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neilce36f8d2018-09-13 15:19:08 -0700759 g.P("func init() {")
Joe Tsai9667c482018-12-05 15:42:52 -0800760 g.P(f.protoPackage().Ident("RegisterFile"), "(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ")")
Damien Neil154da982018-09-19 13:21:58 -0700761 for _, enum := range f.allEnums {
762 name := enum.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800763 g.P(f.protoPackage().Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700764 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700765 for _, message := range f.allMessages {
766 if message.Desc.IsMapEntry() {
767 continue
768 }
769
770 name := message.GoIdent.GoName
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800771 g.P(f.protoPackage().Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700772
773 // Types of map fields, sorted by the name of the field message type.
774 var mapFields []*protogen.Field
775 for _, field := range message.Fields {
776 if field.Desc.IsMap() {
777 mapFields = append(mapFields, field)
778 }
779 }
780 sort.Slice(mapFields, func(i, j int) bool {
781 ni := mapFields[i].MessageType.Desc.FullName()
782 nj := mapFields[j].MessageType.Desc.FullName()
783 return ni < nj
784 })
785 for _, field := range mapFields {
786 typeName := string(field.MessageType.Desc.FullName())
787 goType, _ := fieldGoType(g, field)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800788 g.P(f.protoPackage().Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700789 }
790 }
Joe Tsai9667c482018-12-05 15:42:52 -0800791 for _, extension := range f.allExtensions {
792 g.P(f.protoPackage().Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil993c04d2018-09-14 15:41:11 -0700793 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700794 g.P("}")
795 g.P()
796}
797
Damien Neil55fe1c02018-09-17 15:11:24 -0700798// deprecationComment returns a standard deprecation comment if deprecated is true.
799func deprecationComment(deprecated bool) string {
800 if !deprecated {
801 return ""
802 }
803 return "// Deprecated: Do not use."
804}
805
Damien Neilea7baf42018-09-28 14:23:44 -0700806func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700807 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700808 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700809 g.P()
810 }
811}
812
813// Names of messages and enums for which we will generate XXX_WellKnownType methods.
814var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700815 "google.protobuf.Any": true,
816 "google.protobuf.Duration": true,
817 "google.protobuf.Empty": true,
818 "google.protobuf.Struct": true,
819 "google.protobuf.Timestamp": true,
820
821 "google.protobuf.BoolValue": true,
822 "google.protobuf.BytesValue": true,
823 "google.protobuf.DoubleValue": true,
824 "google.protobuf.FloatValue": true,
825 "google.protobuf.Int32Value": true,
826 "google.protobuf.Int64Value": true,
827 "google.protobuf.ListValue": true,
828 "google.protobuf.NullValue": true,
829 "google.protobuf.StringValue": true,
830 "google.protobuf.UInt32Value": true,
831 "google.protobuf.UInt64Value": true,
832 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700833}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800834
835// genOneofField generates the struct field for a oneof.
836func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
837 if g.PrintLeadingComments(oneof.Location) {
838 g.P("//")
839 }
840 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
841 for _, field := range oneof.Fields {
842 g.PrintLeadingComments(field.Location)
843 g.P("//\t*", fieldOneofType(field))
844 }
845 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
846 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
847}
848
849// genOneofTypes generates the interface type used for a oneof field,
850// and the wrapper types that satisfy that interface.
851//
852// It also generates the getter method for the parent oneof field
853// (but not the member fields).
854func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
855 ifName := oneofInterfaceName(oneof)
856 g.P("type ", ifName, " interface {")
857 g.P(ifName, "()")
858 g.P("}")
859 g.P()
860 for _, field := range oneof.Fields {
861 name := fieldOneofType(field)
862 g.Annotate(name.GoName, field.Location)
863 g.Annotate(name.GoName+"."+field.GoName, field.Location)
864 g.P("type ", name, " struct {")
865 goType, _ := fieldGoType(g, field)
866 tags := []string{
867 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
868 }
869 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
870 g.P("}")
871 g.P()
872 }
873 for _, field := range oneof.Fields {
874 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
875 g.P()
876 }
877 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
878 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
879 g.P("if m != nil {")
880 g.P("return m.", oneofFieldName(oneof))
881 g.P("}")
882 g.P("return nil")
883 g.P("}")
884 g.P()
885}
886
887// oneofFieldName returns the name of the struct field holding the oneof value.
888//
889// This function is trivial, but pulling out the name like this makes it easier
890// to experiment with alternative oneof implementations.
891func oneofFieldName(oneof *protogen.Oneof) string {
892 return oneof.GoName
893}
894
895// oneofInterfaceName returns the name of the interface type implemented by
896// the oneof field value types.
897func oneofInterfaceName(oneof *protogen.Oneof) string {
898 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
899}
900
901// genOneofWrappers generates the XXX_OneofWrappers method for a message.
902func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
903 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
904 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
905 g.P("return []interface{}{")
906 for _, oneof := range message.Oneofs {
907 for _, field := range oneof.Fields {
908 g.P("(*", fieldOneofType(field), ")(nil),")
909 }
910 }
911 g.P("}")
912 g.P("}")
913 g.P()
914}
915
916// fieldOneofType returns the wrapper type used to represent a field in a oneof.
917func fieldOneofType(field *protogen.Field) protogen.GoIdent {
918 ident := protogen.GoIdent{
919 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
920 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
921 }
922 // Check for collisions with nested messages or enums.
923 //
924 // This conflict resolution is incomplete: Among other things, it
925 // does not consider collisions with other oneof field types.
926 //
927 // TODO: Consider dropping this entirely. Detecting conflicts and
928 // producing an error is almost certainly better than permuting
929 // field and type names in mostly unpredictable ways.
930Loop:
931 for {
932 for _, message := range field.ParentMessage.Messages {
933 if message.GoIdent == ident {
934 ident.GoName += "_"
935 continue Loop
936 }
937 }
938 for _, enum := range field.ParentMessage.Enums {
939 if enum.GoIdent == ident {
940 ident.GoName += "_"
941 continue Loop
942 }
943 }
944 return ident
945 }
946}