blob: f204853d5a5afa7cce0a8671f9112373a08035f7 [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 Tsai1af1de02019-03-01 16:12:32 -080021 "github.com/golang/protobuf/v2/internal/descfield"
Joe Tsai05828db2018-11-01 13:52:16 -070022 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai01ab2962018-09-21 17:44:00 -070023 "github.com/golang/protobuf/v2/protogen"
24 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080025
26 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070027)
28
Joe Tsaic1c17aa2018-11-16 11:14:14 -080029const (
Joe Tsai24ceb2b2018-12-04 22:53:56 -080030 mathPackage = protogen.GoImportPath("math")
31 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
32 protoapiPackage = protogen.GoImportPath("github.com/golang/protobuf/protoapi")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080033)
Damien Neil46abb572018-09-07 12:45:37 -070034
Damien Neild39efc82018-09-24 12:38:10 -070035type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070036 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080037
38 // vars containing the raw wire-encoded and compressed FileDescriptorProto.
39 descriptorRawVar string
40 descriptorGzipVar string
Joe Tsaib6405bd2018-11-15 14:44:37 -080041
Joe Tsai9667c482018-12-05 15:42:52 -080042 allEnums []*protogen.Enum
43 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
44 allMessages []*protogen.Message
45 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
46 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070047}
48
Joe Tsai24ceb2b2018-12-04 22:53:56 -080049// protoPackage returns the package to import, which is either the protoPackage
50// or the protoapiPackage constant.
51//
52// This special casing exists because we are unable to move InternalMessageInfo
53// to protoapi since the implementation behind that logic is heavy and
54// too intricately connected to other parts of the proto package.
55// The descriptor proto is special in that it avoids using InternalMessageInfo
56// so that it is able to depend solely on protoapi and break its dependency
57// on the proto package. It is still semantically correct for descriptor to
58// avoid using InternalMessageInfo, but it does incur some performance penalty.
59// This is acceptable for descriptor, which is a single proto file and is not
60// known to be in the hot path for any code.
61//
62// TODO: Remove this special-casing when the table-driven implementation has
63// been ported over to v2.
64func (f *fileInfo) protoPackage() protogen.GoImportPath {
65 if isDescriptor(f.File) {
66 return protoapiPackage
67 }
68 return protoPackage
69}
70
Damien Neil9c420a62018-09-27 15:26:33 -070071// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080072func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
73 filename := file.GeneratedFilenamePrefix + ".pb.go"
74 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070075 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070076 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070077 }
78
Damien Neil8012b442019-01-18 09:32:24 -080079 // Collect all enums, messages, and extensions in "flattened ordering".
80 // See fileinit.FileBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080081 f.allEnums = append(f.allEnums, f.Enums...)
82 f.allMessages = append(f.allMessages, f.Messages...)
83 f.allExtensions = append(f.allExtensions, f.Extensions...)
84 walkMessages(f.Messages, func(m *protogen.Message) {
85 f.allEnums = append(f.allEnums, m.Enums...)
86 f.allMessages = append(f.allMessages, m.Messages...)
87 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070088 })
Damien Neilce36f8d2018-09-13 15:19:08 -070089
Joe Tsai9667c482018-12-05 15:42:52 -080090 // Derive a reverse mapping of enum and message pointers to their index
91 // in allEnums and allMessages.
92 if len(f.allEnums) > 0 {
93 f.allEnumsByPtr = make(map[*protogen.Enum]int)
94 for i, e := range f.allEnums {
95 f.allEnumsByPtr[e] = i
96 }
97 }
98 if len(f.allMessages) > 0 {
99 f.allMessagesByPtr = make(map[*protogen.Message]int)
100 for i, m := range f.allMessages {
101 f.allMessagesByPtr[m] = i
102 }
103 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800104
Joe Tsai40692112019-02-27 20:25:51 -0800105 // Determine the name of the var holding the file descriptor.
106 f.descriptorRawVar = "xxx_" + f.GoDescriptorIdent.GoName + "_rawdesc"
Damien Neil8012b442019-01-18 09:32:24 -0800107 f.descriptorGzipVar = f.descriptorRawVar + "_gzipped"
Damien Neil46abb572018-09-07 12:45:37 -0700108
Damien Neil220c2022018-08-15 11:24:18 -0700109 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700110 if f.Proto.GetOptions().GetDeprecated() {
111 g.P("// ", f.Desc.Path(), " is a deprecated file.")
112 } else {
113 g.P("// source: ", f.Desc.Path())
114 }
Damien Neil220c2022018-08-15 11:24:18 -0700115 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -0700116 g.PrintLeadingComments(protogen.Location{
117 SourceFile: f.Proto.GetName(),
Joe Tsai1af1de02019-03-01 16:12:32 -0800118 Path: []int32{descfield.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700119 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700120 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700121 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700122 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700123
Damien Neil73ac8852018-09-17 15:11:24 -0700124 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
125 genImport(gen, g, f, imps.Get(i))
126 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700127 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700128 genEnum(gen, g, f, enum)
129 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700130 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700131 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700132 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700133 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700134
Damien Neilce36f8d2018-09-13 15:19:08 -0700135 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700136 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800137 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800138
139 return g
Damien Neil7779e052018-09-07 14:14:06 -0700140}
141
Damien Neil73ac8852018-09-17 15:11:24 -0700142// walkMessages calls f on each message and all of its descendants.
143func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
144 for _, m := range messages {
145 f(m)
146 walkMessages(m.Messages, f)
147 }
148}
149
Damien Neild39efc82018-09-24 12:38:10 -0700150func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700151 impFile, ok := gen.FileByName(imp.Path())
152 if !ok {
153 return
154 }
155 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700156 // Don't generate imports or aliases for types in the same Go package.
157 return
158 }
Damien Neil40a08052018-10-29 09:07:41 -0700159 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700160 // referenced, because other code and tools depend on having the
161 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700162 if !imp.IsWeak {
163 g.Import(impFile.GoImportPath)
164 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700165 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700166 return
167 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800168
169 // Generate public imports by generating the imported file, parsing it,
170 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800171 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800172 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800173 b, err := impGen.Content()
174 if err != nil {
175 gen.Error(err)
176 return
177 }
178 fset := token.NewFileSet()
179 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
180 if err != nil {
181 gen.Error(err)
182 return
183 }
Damien Neila7cbd062019-01-06 16:29:14 -0800184 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800185 // Don't import unexported symbols.
186 r, _ := utf8.DecodeRuneInString(name)
187 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700188 return
189 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800190 // Don't import the FileDescriptor.
191 if name == impFile.GoDescriptorIdent.GoName {
192 return
193 }
Damien Neila7cbd062019-01-06 16:29:14 -0800194 // Don't import decls referencing a symbol defined in another package.
195 // i.e., don't import decls which are themselves public imports:
196 //
197 // type T = somepackage.T
198 if _, ok := expr.(*ast.SelectorExpr); ok {
199 return
200 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800201 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
202 }
203 g.P("// Symbols defined in public import of ", imp.Path())
204 g.P()
205 for _, decl := range astFile.Decls {
206 switch decl := decl.(type) {
207 case *ast.GenDecl:
208 for _, spec := range decl.Specs {
209 switch spec := spec.(type) {
210 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800211 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800212 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800213 for i, name := range spec.Names {
214 var expr ast.Expr
215 if i < len(spec.Values) {
216 expr = spec.Values[i]
217 }
218 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800219 }
220 case *ast.ImportSpec:
221 default:
222 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800223 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700224 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700225 }
Damien Neil6b541312018-10-29 09:14:14 -0700226 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700227 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700228}
229
Damien Neild39efc82018-09-24 12:38:10 -0700230func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700231 // Trim the source_code_info from the descriptor.
232 // Marshal and gzip it.
Joe Tsaie1f8d502018-11-26 18:55:29 -0800233 descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto)
Damien Neil7779e052018-09-07 14:14:06 -0700234 descProto.SourceCodeInfo = nil
235 b, err := proto.Marshal(descProto)
236 if err != nil {
237 gen.Error(err)
238 return
239 }
Damien Neil7779e052018-09-07 14:14:06 -0700240
Damien Neil8012b442019-01-18 09:32:24 -0800241 g.P("var ", f.descriptorRawVar, " = []byte{")
242 g.P("// ", len(b), " bytes of the wire-encoded FileDescriptorProto")
Damien Neil7779e052018-09-07 14:14:06 -0700243 for len(b) > 0 {
244 n := 16
245 if n > len(b) {
246 n = len(b)
247 }
248
249 s := ""
250 for _, c := range b[:n] {
251 s += fmt.Sprintf("0x%02x,", c)
252 }
253 g.P(s)
254
255 b = b[n:]
256 }
257 g.P("}")
258 g.P()
Damien Neil8012b442019-01-18 09:32:24 -0800259
Joe Tsaicf81e672019-02-28 14:08:31 -0800260 // TODO: Modify CompressGZIP to lazy encode? Currently, the GZIP'd form
261 // is eagerly registered in v1, preventing any benefit from lazy encoding.
Joe Tsai8e506a82019-03-16 00:05:34 -0700262 g.P("var ", f.descriptorGzipVar, " = ", protoimplPackage.Ident("X"), ".CompressGZIP(", f.descriptorRawVar, ")")
Damien Neil8012b442019-01-18 09:32:24 -0800263 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700264}
Damien Neilc7d07d92018-08-22 13:46:02 -0700265
Damien Neild39efc82018-09-24 12:38:10 -0700266func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700267 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700268 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700269 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800270 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700271 g.P("const (")
272 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700273 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700274 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700275 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800276 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700277 }
278 g.P(")")
279 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800280
281 // Generate support for protobuf reflection.
282 genReflectEnum(gen, g, f, enum)
283
Damien Neil46abb572018-09-07 12:45:37 -0700284 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsai8e506a82019-03-16 00:05:34 -0700285 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700286 g.P("var ", nameMap, " = map[int32]string{")
287 generated := make(map[protoreflect.EnumNumber]bool)
288 for _, value := range enum.Values {
289 duplicate := ""
290 if _, present := generated[value.Desc.Number()]; present {
291 duplicate = "// Duplicate value: "
292 }
293 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
294 generated[value.Desc.Number()] = true
295 }
296 g.P("}")
297 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700298
Damien Neil46abb572018-09-07 12:45:37 -0700299 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsai8e506a82019-03-16 00:05:34 -0700300 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700301 g.P("var ", valueMap, " = map[string]int32{")
302 for _, value := range enum.Values {
303 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
304 }
305 g.P("}")
306 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700307
Damien Neil46abb572018-09-07 12:45:37 -0700308 if enum.Desc.Syntax() != protoreflect.Proto3 {
309 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700310 g.P("return &x")
Damien Neil46abb572018-09-07 12:45:37 -0700311 g.P("}")
312 g.P()
313 }
314 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700315 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Type(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700316 g.P("}")
317 g.P()
318
Joe Tsai73903462018-12-14 12:22:41 -0800319 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700320 g.P("// Deprecated: Do not use.")
321 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
322 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Type(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700323 g.P("if err != nil {")
324 g.P("return err")
325 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700326 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700327 g.P("return nil")
328 g.P("}")
329 g.P()
330 }
331
332 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700333 for i := 1; i < len(enum.Location.Path); i += 2 {
334 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700335 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700336 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700337 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800338 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neil46abb572018-09-07 12:45:37 -0700339 g.P("}")
340 g.P()
341
Damien Neilea7baf42018-09-28 14:23:44 -0700342 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700343}
344
Damien Neil658051b2018-09-10 12:26:21 -0700345// enumRegistryName returns the name used to register an enum with the proto
346// package registry.
347//
348// Confusingly, this is <proto_package>.<go_ident>. This probably should have
349// been the full name of the proto enum type instead, but changing it at this
350// point would require thought.
351func enumRegistryName(enum *protogen.Enum) string {
352 // Find the FileDescriptor for this enum.
353 var desc protoreflect.Descriptor = enum.Desc
354 for {
355 p, ok := desc.Parent()
356 if !ok {
357 break
358 }
359 desc = p
360 }
361 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700362 if fdesc.Package() == "" {
363 return enum.GoIdent.GoName
364 }
Damien Neil658051b2018-09-10 12:26:21 -0700365 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
366}
367
Damien Neild39efc82018-09-24 12:38:10 -0700368func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700369 if message.Desc.IsMapEntry() {
370 return
371 }
372
Damien Neilba1159f2018-10-17 12:53:18 -0700373 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800374 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700375 if hasComment {
376 g.P("//")
377 }
378 g.P(deprecationComment(true))
379 }
Damien Neil162c1272018-10-04 12:42:37 -0700380 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700381 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700382 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700383 if field.OneofType != nil {
384 // It would be a bit simpler to iterate over the oneofs below,
385 // but generating the field here keeps the contents of the Go
386 // struct in the same order as the contents of the source
387 // .proto file.
388 if field == field.OneofType.Fields[0] {
389 genOneofField(gen, g, f, message, field.OneofType)
390 }
Damien Neil658051b2018-09-10 12:26:21 -0700391 continue
392 }
Damien Neilba1159f2018-10-17 12:53:18 -0700393 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700394 goType, pointer := fieldGoType(g, field)
395 if pointer {
396 goType = "*" + goType
397 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700398 tags := []string{
399 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
400 fmt.Sprintf("json:%q", fieldJSONTag(field)),
401 }
402 if field.Desc.IsMap() {
403 key := field.MessageType.Fields[0]
404 val := field.MessageType.Fields[1]
405 tags = append(tags,
406 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
407 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
408 )
409 }
Damien Neil162c1272018-10-04 12:42:37 -0700410 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700411 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800412 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700413 }
414 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700415
416 if message.Desc.ExtensionRanges().Len() > 0 {
417 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800418 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700419 tags = append(tags, `protobuf_messageset:"1"`)
420 }
421 tags = append(tags, `json:"-"`)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800422 g.P(f.protoPackage().Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700423 }
Damien Neil658051b2018-09-10 12:26:21 -0700424 g.P("XXX_unrecognized []byte `json:\"-\"`")
425 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700426 g.P("}")
427 g.P()
428
Joe Tsaib6405bd2018-11-15 14:44:37 -0800429 // Generate support for protobuf reflection.
430 genReflectMessage(gen, g, f, message)
431
Damien Neila1c6abc2018-09-12 13:36:34 -0700432 // Reset
433 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
434 // String
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800435 g.P("func (m *", message.GoIdent, ") String() string { return ", f.protoPackage().Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700436 // ProtoMessage
437 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
438 // Descriptor
439 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700440 for i := 1; i < len(message.Location.Path); i += 2 {
441 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700442 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700443 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
Damien Neila1c6abc2018-09-12 13:36:34 -0700444 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800445 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neila1c6abc2018-09-12 13:36:34 -0700446 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700447 g.P()
448
449 // ExtensionRangeArray
450 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800451 protoExtRange := f.protoPackage().Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700452 extRangeVar := "extRange_" + message.GoIdent.GoName
453 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
454 for i := 0; i < extranges.Len(); i++ {
455 r := extranges.Get(i)
456 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
457 }
458 g.P("}")
459 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700460 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700461 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
462 g.P("return ", extRangeVar)
463 g.P("}")
464 g.P()
465 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700466
Damien Neilea7baf42018-09-28 14:23:44 -0700467 genWellKnownType(g, "*", message.GoIdent, message.Desc)
468
Damien Neila1c6abc2018-09-12 13:36:34 -0700469 // Table-driven proto support.
470 //
471 // TODO: It does not scale to keep adding another method for every
472 // operation on protos that we want to switch over to using the
473 // table-driven approach. Instead, we should only add a single method
474 // that allows getting access to the *InternalMessageInfo struct and then
475 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800476 if !isDescriptor(f.File) {
477 // NOTE: We avoid adding table-driven support for descriptor proto
478 // since this depends on the v1 proto package, which would eventually
479 // need to depend on the descriptor itself.
480 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
481 // XXX_Unmarshal
482 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
483 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
484 g.P("}")
485 // XXX_Marshal
486 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
487 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
488 g.P("}")
489 // XXX_Merge
490 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
491 g.P(messageInfoVar, ".Merge(m, src)")
492 g.P("}")
493 // XXX_Size
494 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
495 g.P("return ", messageInfoVar, ".Size(m)")
496 g.P("}")
497 // XXX_DiscardUnknown
498 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
499 g.P(messageInfoVar, ".DiscardUnknown(m)")
500 g.P("}")
501 g.P()
502 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
503 g.P()
504 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700505
Damien Neilebc699d2018-09-13 08:50:13 -0700506 // Constants and vars holding the default values of fields.
507 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800508 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700509 continue
510 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700511 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700512 def := field.Desc.Default()
513 switch field.Desc.Kind() {
514 case protoreflect.StringKind:
515 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
516 case protoreflect.BytesKind:
517 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
518 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700519 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700520 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700521 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700522 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
523 case protoreflect.FloatKind, protoreflect.DoubleKind:
524 // Floating point numbers need extra handling for -Inf/Inf/NaN.
525 f := field.Desc.Default().Float()
526 goType := "float64"
527 if field.Desc.Kind() == protoreflect.FloatKind {
528 goType = "float32"
529 }
530 // funcCall returns a call to a function in the math package,
531 // possibly converting the result to float32.
532 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800533 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700534 if goType != "float64" {
535 s = goType + "(" + s + ")"
536 }
537 return s
538 }
539 switch {
540 case math.IsInf(f, -1):
541 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
542 case math.IsInf(f, 1):
543 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
544 case math.IsNaN(f):
545 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
546 default:
Damien Neil982684b2018-09-28 14:12:41 -0700547 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700548 }
549 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700550 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700551 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
552 }
553 }
554 g.P()
555
Damien Neil77f82fe2018-09-13 10:59:17 -0700556 // Getters.
557 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700558 if field.OneofType != nil {
559 if field == field.OneofType.Fields[0] {
560 genOneofTypes(gen, g, f, message, field.OneofType)
561 }
562 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700563 goType, pointer := fieldGoType(g, field)
564 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800565 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700566 g.P(deprecationComment(true))
567 }
Damien Neil162c1272018-10-04 12:42:37 -0700568 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700569 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
570 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700571 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700572 g.P("return x.", field.GoName)
573 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700574 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700575 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
576 g.P("if m != nil {")
577 } else {
578 g.P("if m != nil && m.", field.GoName, " != nil {")
579 }
580 star := ""
581 if pointer {
582 star = "*"
583 }
584 g.P("return ", star, " m.", field.GoName)
585 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700586 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700587 g.P("return ", defaultValue)
588 g.P("}")
589 g.P()
590 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700591
Damien Neil1fa78d82018-09-13 13:12:36 -0700592 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800593 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700594 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700595}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700596
Damien Neil77f82fe2018-09-13 10:59:17 -0700597// fieldGoType returns the Go type used for a field.
598//
599// If it returns pointer=true, the struct field is a pointer to the type.
600func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700601 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700602 switch field.Desc.Kind() {
603 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700604 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700605 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700606 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700607 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700608 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700609 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700610 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700611 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700612 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700613 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700615 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700617 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700619 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700620 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700621 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 goType = "[]byte"
623 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700624 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700625 if field.Desc.IsMap() {
626 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
627 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
628 return fmt.Sprintf("map[%v]%v", keyType, valType), false
629 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
631 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700632 }
633 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700634 goType = "[]" + goType
635 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700636 }
Damien Neil44000a12018-10-24 12:31:16 -0700637 // Extension fields always have pointer type, even when defined in a proto3 file.
638 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700639 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700640 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700641 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700642}
643
644func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700645 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700646 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700647 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700648 }
Joe Tsai05828db2018-11-01 13:52:16 -0700649 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700650}
651
Damien Neil77f82fe2018-09-13 10:59:17 -0700652func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
653 if field.Desc.Cardinality() == protoreflect.Repeated {
654 return "nil"
655 }
Joe Tsai9667c482018-12-05 15:42:52 -0800656 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700657 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700658 if field.Desc.Kind() == protoreflect.BytesKind {
659 return "append([]byte(nil), " + defVarName + "...)"
660 }
661 return defVarName
662 }
663 switch field.Desc.Kind() {
664 case protoreflect.BoolKind:
665 return "false"
666 case protoreflect.StringKind:
667 return `""`
668 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
669 return "nil"
670 case protoreflect.EnumKind:
671 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
672 default:
673 return "0"
674 }
675}
676
Damien Neil658051b2018-09-10 12:26:21 -0700677func fieldJSONTag(field *protogen.Field) string {
678 return string(field.Desc.Name()) + ",omitempty"
679}
680
Joe Tsaiafb455e2019-03-14 16:08:22 -0700681func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
682 if len(f.allExtensions) == 0 {
683 return
Damien Neil154da982018-09-19 13:21:58 -0700684 }
685
Joe Tsaiafb455e2019-03-14 16:08:22 -0700686 g.P("var ", extDecsVarName(f), " = []", f.protoPackage().Ident("ExtensionDesc"), "{")
687 for _, extension := range f.allExtensions {
688 // Special case for proto2 message sets: If this extension is extending
689 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
690 // then drop that last component.
691 //
692 // TODO: This should be implemented in the text formatter rather than the generator.
693 // In addition, the situation for when to apply this special case is implemented
694 // differently in other languages:
695 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
696 name := extension.Desc.FullName()
697 if n, ok := isExtensionMessageSetElement(extension); ok {
698 name = n
699 }
700
701 g.P("{")
702 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
703 goType, pointer := fieldGoType(g, extension)
704 if pointer {
705 goType = "*" + goType
706 }
707 g.P("ExtensionType: (", goType, ")(nil),")
708 g.P("Field: ", extension.Desc.Number(), ",")
709 g.P("Name: ", strconv.Quote(string(name)), ",")
710 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
711 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
712 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700713 }
Damien Neil993c04d2018-09-14 15:41:11 -0700714 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700715
716 g.P("var (")
717 for i, extension := range f.allExtensions {
718 ed := extension.Desc
719 targetName := string(ed.ExtendedType().FullName())
720 typeName := ed.Kind().String()
721 switch ed.Kind() {
722 case protoreflect.EnumKind:
723 typeName = string(ed.EnumType().FullName())
724 case protoreflect.MessageKind, protoreflect.GroupKind:
725 typeName = string(ed.MessageType().FullName())
726 }
727 fieldName := string(ed.Name())
728 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
729 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
730 g.P()
731 }
732 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700733}
734
Damien Neil62386962018-10-30 10:35:48 -0700735// isExtensionMessageSetELement returns the adjusted name of an extension
736// which extends proto2.bridge.MessageSet.
737func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800738 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700739 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
740 return "", false
741 }
742 if extension.ParentMessage == nil {
743 // This case shouldn't be given special handling at all--we're
744 // only supposed to drop the ".message_set_extension" for
745 // extensions defined within a message (i.e., the extension
746 // takes the message's name).
747 //
748 // This matches the behavior of the v1 generator, however.
749 //
750 // TODO: See if we can drop this case.
751 name = extension.Desc.FullName()
752 name = name[:len(name)-len("message_set_extension")]
753 return name, true
754 }
755 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700756}
757
Damien Neil993c04d2018-09-14 15:41:11 -0700758// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700759func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700760 name := "E_"
761 if extension.ParentMessage != nil {
762 name += extension.ParentMessage.GoIdent.GoName + "_"
763 }
764 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800765 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700766}
767
Damien Neilce36f8d2018-09-13 15:19:08 -0700768// genInitFunction generates an init function that registers the types in the
769// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700770func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neilce36f8d2018-09-13 15:19:08 -0700771 g.P("func init() {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700772 g.P(protoPackage.Ident("RegisterFile"), "(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorGzipVar, ")")
Damien Neil154da982018-09-19 13:21:58 -0700773 for _, enum := range f.allEnums {
774 name := enum.GoIdent.GoName
Joe Tsai8e506a82019-03-16 00:05:34 -0700775 g.P(protoPackage.Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700776 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700777 for _, message := range f.allMessages {
778 if message.Desc.IsMapEntry() {
779 continue
780 }
781
782 name := message.GoIdent.GoName
Joe Tsai8e506a82019-03-16 00:05:34 -0700783 g.P(protoPackage.Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700784
785 // Types of map fields, sorted by the name of the field message type.
786 var mapFields []*protogen.Field
787 for _, field := range message.Fields {
788 if field.Desc.IsMap() {
789 mapFields = append(mapFields, field)
790 }
791 }
792 sort.Slice(mapFields, func(i, j int) bool {
793 ni := mapFields[i].MessageType.Desc.FullName()
794 nj := mapFields[j].MessageType.Desc.FullName()
795 return ni < nj
796 })
797 for _, field := range mapFields {
798 typeName := string(field.MessageType.Desc.FullName())
799 goType, _ := fieldGoType(g, field)
Joe Tsai8e506a82019-03-16 00:05:34 -0700800 g.P(protoPackage.Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700801 }
802 }
Joe Tsai9667c482018-12-05 15:42:52 -0800803 for _, extension := range f.allExtensions {
Joe Tsai8e506a82019-03-16 00:05:34 -0700804 g.P(protoPackage.Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil993c04d2018-09-14 15:41:11 -0700805 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700806 g.P("}")
807 g.P()
808}
809
Damien Neil55fe1c02018-09-17 15:11:24 -0700810// deprecationComment returns a standard deprecation comment if deprecated is true.
811func deprecationComment(deprecated bool) string {
812 if !deprecated {
813 return ""
814 }
815 return "// Deprecated: Do not use."
816}
817
Damien Neilea7baf42018-09-28 14:23:44 -0700818func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700819 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700820 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700821 g.P()
822 }
823}
824
825// Names of messages and enums for which we will generate XXX_WellKnownType methods.
826var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700827 "google.protobuf.Any": true,
828 "google.protobuf.Duration": true,
829 "google.protobuf.Empty": true,
830 "google.protobuf.Struct": true,
831 "google.protobuf.Timestamp": true,
832
833 "google.protobuf.BoolValue": true,
834 "google.protobuf.BytesValue": true,
835 "google.protobuf.DoubleValue": true,
836 "google.protobuf.FloatValue": true,
837 "google.protobuf.Int32Value": true,
838 "google.protobuf.Int64Value": true,
839 "google.protobuf.ListValue": true,
840 "google.protobuf.NullValue": true,
841 "google.protobuf.StringValue": true,
842 "google.protobuf.UInt32Value": true,
843 "google.protobuf.UInt64Value": true,
844 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700845}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800846
847// genOneofField generates the struct field for a oneof.
848func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
849 if g.PrintLeadingComments(oneof.Location) {
850 g.P("//")
851 }
852 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
853 for _, field := range oneof.Fields {
854 g.PrintLeadingComments(field.Location)
855 g.P("//\t*", fieldOneofType(field))
856 }
857 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
858 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
859}
860
861// genOneofTypes generates the interface type used for a oneof field,
862// and the wrapper types that satisfy that interface.
863//
864// It also generates the getter method for the parent oneof field
865// (but not the member fields).
866func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
867 ifName := oneofInterfaceName(oneof)
868 g.P("type ", ifName, " interface {")
869 g.P(ifName, "()")
870 g.P("}")
871 g.P()
872 for _, field := range oneof.Fields {
873 name := fieldOneofType(field)
874 g.Annotate(name.GoName, field.Location)
875 g.Annotate(name.GoName+"."+field.GoName, field.Location)
876 g.P("type ", name, " struct {")
877 goType, _ := fieldGoType(g, field)
878 tags := []string{
879 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
880 }
881 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
882 g.P("}")
883 g.P()
884 }
885 for _, field := range oneof.Fields {
886 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
887 g.P()
888 }
889 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
890 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
891 g.P("if m != nil {")
892 g.P("return m.", oneofFieldName(oneof))
893 g.P("}")
894 g.P("return nil")
895 g.P("}")
896 g.P()
897}
898
899// oneofFieldName returns the name of the struct field holding the oneof value.
900//
901// This function is trivial, but pulling out the name like this makes it easier
902// to experiment with alternative oneof implementations.
903func oneofFieldName(oneof *protogen.Oneof) string {
904 return oneof.GoName
905}
906
907// oneofInterfaceName returns the name of the interface type implemented by
908// the oneof field value types.
909func oneofInterfaceName(oneof *protogen.Oneof) string {
910 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
911}
912
913// genOneofWrappers generates the XXX_OneofWrappers method for a message.
914func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
915 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
916 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
917 g.P("return []interface{}{")
918 for _, oneof := range message.Oneofs {
919 for _, field := range oneof.Fields {
920 g.P("(*", fieldOneofType(field), ")(nil),")
921 }
922 }
923 g.P("}")
924 g.P("}")
925 g.P()
926}
927
928// fieldOneofType returns the wrapper type used to represent a field in a oneof.
929func fieldOneofType(field *protogen.Field) protogen.GoIdent {
930 ident := protogen.GoIdent{
931 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
932 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
933 }
934 // Check for collisions with nested messages or enums.
935 //
936 // This conflict resolution is incomplete: Among other things, it
937 // does not consider collisions with other oneof field types.
938 //
939 // TODO: Consider dropping this entirely. Detecting conflicts and
940 // producing an error is almost certainly better than permuting
941 // field and type names in mostly unpredictable ways.
942Loop:
943 for {
944 for _, message := range field.ParentMessage.Messages {
945 if message.GoIdent == ident {
946 ident.GoName += "_"
947 continue Loop
948 }
949 }
950 for _, enum := range field.ParentMessage.Enums {
951 if enum.GoIdent == ident {
952 ident.GoName += "_"
953 continue Loop
954 }
955 }
956 return ident
957 }
958}