blob: 70ecbc90a6ea558a695e8790b6a11d3f75723d10 [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
Joe Tsai1af1de02019-03-01 16:12:32 -080020 "github.com/golang/protobuf/v2/internal/descfield"
Joe Tsai05828db2018-11-01 13:52:16 -070021 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsaif31bf262019-03-18 14:54:34 -070022 "github.com/golang/protobuf/v2/proto"
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) {
Joe Tsaif31bf262019-03-18 14:54:34 -0700231 // TODO: Replace this with v2 Clone.
232 descProto := new(descriptorpb.FileDescriptorProto)
233 b, err := proto.Marshal(f.Proto)
234 if err != nil {
235 gen.Error(err)
236 return
237 }
238 if err := proto.Unmarshal(b, descProto); err != nil {
239 gen.Error(err)
240 return
241 }
242
Damien Neil7779e052018-09-07 14:14:06 -0700243 // Trim the source_code_info from the descriptor.
Damien Neil7779e052018-09-07 14:14:06 -0700244 descProto.SourceCodeInfo = nil
Joe Tsaif31bf262019-03-18 14:54:34 -0700245 b, err = proto.MarshalOptions{Deterministic: true}.Marshal(descProto)
Damien Neil7779e052018-09-07 14:14:06 -0700246 if err != nil {
247 gen.Error(err)
248 return
249 }
Damien Neil7779e052018-09-07 14:14:06 -0700250
Damien Neil8012b442019-01-18 09:32:24 -0800251 g.P("var ", f.descriptorRawVar, " = []byte{")
252 g.P("// ", len(b), " bytes of the wire-encoded FileDescriptorProto")
Damien Neil7779e052018-09-07 14:14:06 -0700253 for len(b) > 0 {
254 n := 16
255 if n > len(b) {
256 n = len(b)
257 }
258
259 s := ""
260 for _, c := range b[:n] {
261 s += fmt.Sprintf("0x%02x,", c)
262 }
263 g.P(s)
264
265 b = b[n:]
266 }
267 g.P("}")
268 g.P()
Damien Neil8012b442019-01-18 09:32:24 -0800269
Joe Tsaicf81e672019-02-28 14:08:31 -0800270 // TODO: Modify CompressGZIP to lazy encode? Currently, the GZIP'd form
271 // is eagerly registered in v1, preventing any benefit from lazy encoding.
Joe Tsai8e506a82019-03-16 00:05:34 -0700272 g.P("var ", f.descriptorGzipVar, " = ", protoimplPackage.Ident("X"), ".CompressGZIP(", f.descriptorRawVar, ")")
Damien Neil8012b442019-01-18 09:32:24 -0800273 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700274}
Damien Neilc7d07d92018-08-22 13:46:02 -0700275
Damien Neild39efc82018-09-24 12:38:10 -0700276func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700277 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700278 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700279 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800280 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700281 g.P("const (")
282 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700283 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700284 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700285 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800286 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700287 }
288 g.P(")")
289 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800290
291 // Generate support for protobuf reflection.
292 genReflectEnum(gen, g, f, enum)
293
Damien Neil46abb572018-09-07 12:45:37 -0700294 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsai8e506a82019-03-16 00:05:34 -0700295 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700296 g.P("var ", nameMap, " = map[int32]string{")
297 generated := make(map[protoreflect.EnumNumber]bool)
298 for _, value := range enum.Values {
299 duplicate := ""
300 if _, present := generated[value.Desc.Number()]; present {
301 duplicate = "// Duplicate value: "
302 }
303 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
304 generated[value.Desc.Number()] = true
305 }
306 g.P("}")
307 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700308
Damien Neil46abb572018-09-07 12:45:37 -0700309 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsai8e506a82019-03-16 00:05:34 -0700310 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700311 g.P("var ", valueMap, " = map[string]int32{")
312 for _, value := range enum.Values {
313 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
314 }
315 g.P("}")
316 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700317
Damien Neil46abb572018-09-07 12:45:37 -0700318 if enum.Desc.Syntax() != protoreflect.Proto3 {
319 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700320 g.P("return &x")
Damien Neil46abb572018-09-07 12:45:37 -0700321 g.P("}")
322 g.P()
323 }
324 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700325 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Type(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700326 g.P("}")
327 g.P()
328
Joe Tsai73903462018-12-14 12:22:41 -0800329 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700330 g.P("// Deprecated: Do not use.")
331 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
332 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Type(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700333 g.P("if err != nil {")
334 g.P("return err")
335 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700336 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700337 g.P("return nil")
338 g.P("}")
339 g.P()
340 }
341
342 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700343 for i := 1; i < len(enum.Location.Path); i += 2 {
344 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700345 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700346 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700347 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800348 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neil46abb572018-09-07 12:45:37 -0700349 g.P("}")
350 g.P()
351
Damien Neilea7baf42018-09-28 14:23:44 -0700352 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700353}
354
Damien Neil658051b2018-09-10 12:26:21 -0700355// enumRegistryName returns the name used to register an enum with the proto
356// package registry.
357//
358// Confusingly, this is <proto_package>.<go_ident>. This probably should have
359// been the full name of the proto enum type instead, but changing it at this
360// point would require thought.
361func enumRegistryName(enum *protogen.Enum) string {
362 // Find the FileDescriptor for this enum.
363 var desc protoreflect.Descriptor = enum.Desc
364 for {
365 p, ok := desc.Parent()
366 if !ok {
367 break
368 }
369 desc = p
370 }
371 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700372 if fdesc.Package() == "" {
373 return enum.GoIdent.GoName
374 }
Damien Neil658051b2018-09-10 12:26:21 -0700375 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
376}
377
Damien Neild39efc82018-09-24 12:38:10 -0700378func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700379 if message.Desc.IsMapEntry() {
380 return
381 }
382
Damien Neilba1159f2018-10-17 12:53:18 -0700383 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800384 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700385 if hasComment {
386 g.P("//")
387 }
388 g.P(deprecationComment(true))
389 }
Damien Neil162c1272018-10-04 12:42:37 -0700390 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700391 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700392 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700393 if field.OneofType != nil {
394 // It would be a bit simpler to iterate over the oneofs below,
395 // but generating the field here keeps the contents of the Go
396 // struct in the same order as the contents of the source
397 // .proto file.
398 if field == field.OneofType.Fields[0] {
399 genOneofField(gen, g, f, message, field.OneofType)
400 }
Damien Neil658051b2018-09-10 12:26:21 -0700401 continue
402 }
Damien Neilba1159f2018-10-17 12:53:18 -0700403 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700404 goType, pointer := fieldGoType(g, field)
405 if pointer {
406 goType = "*" + goType
407 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700408 tags := []string{
409 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
410 fmt.Sprintf("json:%q", fieldJSONTag(field)),
411 }
412 if field.Desc.IsMap() {
413 key := field.MessageType.Fields[0]
414 val := field.MessageType.Fields[1]
415 tags = append(tags,
416 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
417 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
418 )
419 }
Damien Neil162c1272018-10-04 12:42:37 -0700420 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700421 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800422 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700423 }
424 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700425
426 if message.Desc.ExtensionRanges().Len() > 0 {
427 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800428 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700429 tags = append(tags, `protobuf_messageset:"1"`)
430 }
431 tags = append(tags, `json:"-"`)
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800432 g.P(f.protoPackage().Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700433 }
Damien Neil658051b2018-09-10 12:26:21 -0700434 g.P("XXX_unrecognized []byte `json:\"-\"`")
435 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700436 g.P("}")
437 g.P()
438
Joe Tsaib6405bd2018-11-15 14:44:37 -0800439 // Generate support for protobuf reflection.
440 genReflectMessage(gen, g, f, message)
441
Damien Neila1c6abc2018-09-12 13:36:34 -0700442 // Reset
443 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
444 // String
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800445 g.P("func (m *", message.GoIdent, ") String() string { return ", f.protoPackage().Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700446 // ProtoMessage
447 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
448 // Descriptor
449 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700450 for i := 1; i < len(message.Location.Path); i += 2 {
451 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700452 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700453 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
Damien Neila1c6abc2018-09-12 13:36:34 -0700454 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800455 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neila1c6abc2018-09-12 13:36:34 -0700456 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700457 g.P()
458
459 // ExtensionRangeArray
460 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800461 protoExtRange := f.protoPackage().Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700462 extRangeVar := "extRange_" + message.GoIdent.GoName
463 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
464 for i := 0; i < extranges.Len(); i++ {
465 r := extranges.Get(i)
466 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
467 }
468 g.P("}")
469 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700470 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700471 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
472 g.P("return ", extRangeVar)
473 g.P("}")
474 g.P()
475 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700476
Damien Neilea7baf42018-09-28 14:23:44 -0700477 genWellKnownType(g, "*", message.GoIdent, message.Desc)
478
Damien Neila1c6abc2018-09-12 13:36:34 -0700479 // Table-driven proto support.
480 //
481 // TODO: It does not scale to keep adding another method for every
482 // operation on protos that we want to switch over to using the
483 // table-driven approach. Instead, we should only add a single method
484 // that allows getting access to the *InternalMessageInfo struct and then
485 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800486 if !isDescriptor(f.File) {
487 // NOTE: We avoid adding table-driven support for descriptor proto
488 // since this depends on the v1 proto package, which would eventually
489 // need to depend on the descriptor itself.
490 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
491 // XXX_Unmarshal
492 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
493 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
494 g.P("}")
495 // XXX_Marshal
496 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
497 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
498 g.P("}")
499 // XXX_Merge
500 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
501 g.P(messageInfoVar, ".Merge(m, src)")
502 g.P("}")
503 // XXX_Size
504 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
505 g.P("return ", messageInfoVar, ".Size(m)")
506 g.P("}")
507 // XXX_DiscardUnknown
508 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
509 g.P(messageInfoVar, ".DiscardUnknown(m)")
510 g.P("}")
511 g.P()
512 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
513 g.P()
514 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700515
Damien Neilebc699d2018-09-13 08:50:13 -0700516 // Constants and vars holding the default values of fields.
517 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800518 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700519 continue
520 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700521 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700522 def := field.Desc.Default()
523 switch field.Desc.Kind() {
524 case protoreflect.StringKind:
525 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
526 case protoreflect.BytesKind:
527 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
528 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700529 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700530 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700531 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700532 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
533 case protoreflect.FloatKind, protoreflect.DoubleKind:
534 // Floating point numbers need extra handling for -Inf/Inf/NaN.
535 f := field.Desc.Default().Float()
536 goType := "float64"
537 if field.Desc.Kind() == protoreflect.FloatKind {
538 goType = "float32"
539 }
540 // funcCall returns a call to a function in the math package,
541 // possibly converting the result to float32.
542 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800543 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700544 if goType != "float64" {
545 s = goType + "(" + s + ")"
546 }
547 return s
548 }
549 switch {
550 case math.IsInf(f, -1):
551 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
552 case math.IsInf(f, 1):
553 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
554 case math.IsNaN(f):
555 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
556 default:
Damien Neil982684b2018-09-28 14:12:41 -0700557 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700558 }
559 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700560 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700561 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
562 }
563 }
564 g.P()
565
Damien Neil77f82fe2018-09-13 10:59:17 -0700566 // Getters.
567 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700568 if field.OneofType != nil {
569 if field == field.OneofType.Fields[0] {
570 genOneofTypes(gen, g, f, message, field.OneofType)
571 }
572 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700573 goType, pointer := fieldGoType(g, field)
574 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800575 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700576 g.P(deprecationComment(true))
577 }
Damien Neil162c1272018-10-04 12:42:37 -0700578 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700579 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
580 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700581 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700582 g.P("return x.", field.GoName)
583 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700584 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700585 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
586 g.P("if m != nil {")
587 } else {
588 g.P("if m != nil && m.", field.GoName, " != nil {")
589 }
590 star := ""
591 if pointer {
592 star = "*"
593 }
594 g.P("return ", star, " m.", field.GoName)
595 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700596 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700597 g.P("return ", defaultValue)
598 g.P("}")
599 g.P()
600 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700601
Damien Neil1fa78d82018-09-13 13:12:36 -0700602 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800603 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700604 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700605}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700606
Damien Neil77f82fe2018-09-13 10:59:17 -0700607// fieldGoType returns the Go type used for a field.
608//
609// If it returns pointer=true, the struct field is a pointer to the type.
610func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700611 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700612 switch field.Desc.Kind() {
613 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700615 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700617 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700619 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700620 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700621 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700623 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700625 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700626 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700627 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700629 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700631 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700632 goType = "[]byte"
633 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700634 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700635 if field.Desc.IsMap() {
636 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
637 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
638 return fmt.Sprintf("map[%v]%v", keyType, valType), false
639 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700640 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
641 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700642 }
643 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700644 goType = "[]" + goType
645 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700646 }
Damien Neil44000a12018-10-24 12:31:16 -0700647 // Extension fields always have pointer type, even when defined in a proto3 file.
648 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700649 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700650 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700651 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700652}
653
654func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700655 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700656 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700657 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700658 }
Joe Tsai05828db2018-11-01 13:52:16 -0700659 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700660}
661
Damien Neil77f82fe2018-09-13 10:59:17 -0700662func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
663 if field.Desc.Cardinality() == protoreflect.Repeated {
664 return "nil"
665 }
Joe Tsai9667c482018-12-05 15:42:52 -0800666 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700667 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700668 if field.Desc.Kind() == protoreflect.BytesKind {
669 return "append([]byte(nil), " + defVarName + "...)"
670 }
671 return defVarName
672 }
673 switch field.Desc.Kind() {
674 case protoreflect.BoolKind:
675 return "false"
676 case protoreflect.StringKind:
677 return `""`
678 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
679 return "nil"
680 case protoreflect.EnumKind:
681 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
682 default:
683 return "0"
684 }
685}
686
Damien Neil658051b2018-09-10 12:26:21 -0700687func fieldJSONTag(field *protogen.Field) string {
688 return string(field.Desc.Name()) + ",omitempty"
689}
690
Joe Tsaiafb455e2019-03-14 16:08:22 -0700691func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
692 if len(f.allExtensions) == 0 {
693 return
Damien Neil154da982018-09-19 13:21:58 -0700694 }
695
Joe Tsaiafb455e2019-03-14 16:08:22 -0700696 g.P("var ", extDecsVarName(f), " = []", f.protoPackage().Ident("ExtensionDesc"), "{")
697 for _, extension := range f.allExtensions {
698 // Special case for proto2 message sets: If this extension is extending
699 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
700 // then drop that last component.
701 //
702 // TODO: This should be implemented in the text formatter rather than the generator.
703 // In addition, the situation for when to apply this special case is implemented
704 // differently in other languages:
705 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
706 name := extension.Desc.FullName()
707 if n, ok := isExtensionMessageSetElement(extension); ok {
708 name = n
709 }
710
711 g.P("{")
712 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
713 goType, pointer := fieldGoType(g, extension)
714 if pointer {
715 goType = "*" + goType
716 }
717 g.P("ExtensionType: (", goType, ")(nil),")
718 g.P("Field: ", extension.Desc.Number(), ",")
719 g.P("Name: ", strconv.Quote(string(name)), ",")
720 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
721 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
722 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700723 }
Damien Neil993c04d2018-09-14 15:41:11 -0700724 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700725
726 g.P("var (")
727 for i, extension := range f.allExtensions {
728 ed := extension.Desc
729 targetName := string(ed.ExtendedType().FullName())
730 typeName := ed.Kind().String()
731 switch ed.Kind() {
732 case protoreflect.EnumKind:
733 typeName = string(ed.EnumType().FullName())
734 case protoreflect.MessageKind, protoreflect.GroupKind:
735 typeName = string(ed.MessageType().FullName())
736 }
737 fieldName := string(ed.Name())
738 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
739 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
740 g.P()
741 }
742 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700743}
744
Damien Neil62386962018-10-30 10:35:48 -0700745// isExtensionMessageSetELement returns the adjusted name of an extension
746// which extends proto2.bridge.MessageSet.
747func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800748 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700749 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
750 return "", false
751 }
752 if extension.ParentMessage == nil {
753 // This case shouldn't be given special handling at all--we're
754 // only supposed to drop the ".message_set_extension" for
755 // extensions defined within a message (i.e., the extension
756 // takes the message's name).
757 //
758 // This matches the behavior of the v1 generator, however.
759 //
760 // TODO: See if we can drop this case.
761 name = extension.Desc.FullName()
762 name = name[:len(name)-len("message_set_extension")]
763 return name, true
764 }
765 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700766}
767
Damien Neil993c04d2018-09-14 15:41:11 -0700768// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700769func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700770 name := "E_"
771 if extension.ParentMessage != nil {
772 name += extension.ParentMessage.GoIdent.GoName + "_"
773 }
774 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800775 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700776}
777
Damien Neilce36f8d2018-09-13 15:19:08 -0700778// genInitFunction generates an init function that registers the types in the
779// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700780func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Joe Tsai08cd8842019-03-18 13:46:39 -0700781 // TODO: Remove this function when we always register with v2.
782 if isDescriptor(f.File) {
783 return
784 }
785
Damien Neilce36f8d2018-09-13 15:19:08 -0700786 g.P("func init() {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700787 g.P(protoPackage.Ident("RegisterFile"), "(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorGzipVar, ")")
Damien Neil154da982018-09-19 13:21:58 -0700788 for _, enum := range f.allEnums {
789 name := enum.GoIdent.GoName
Joe Tsai8e506a82019-03-16 00:05:34 -0700790 g.P(protoPackage.Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700791 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700792 for _, message := range f.allMessages {
793 if message.Desc.IsMapEntry() {
794 continue
795 }
796
797 name := message.GoIdent.GoName
Joe Tsai8e506a82019-03-16 00:05:34 -0700798 g.P(protoPackage.Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700799
800 // Types of map fields, sorted by the name of the field message type.
801 var mapFields []*protogen.Field
802 for _, field := range message.Fields {
803 if field.Desc.IsMap() {
804 mapFields = append(mapFields, field)
805 }
806 }
807 sort.Slice(mapFields, func(i, j int) bool {
808 ni := mapFields[i].MessageType.Desc.FullName()
809 nj := mapFields[j].MessageType.Desc.FullName()
810 return ni < nj
811 })
812 for _, field := range mapFields {
813 typeName := string(field.MessageType.Desc.FullName())
814 goType, _ := fieldGoType(g, field)
Joe Tsai8e506a82019-03-16 00:05:34 -0700815 g.P(protoPackage.Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700816 }
817 }
Joe Tsai9667c482018-12-05 15:42:52 -0800818 for _, extension := range f.allExtensions {
Joe Tsai8e506a82019-03-16 00:05:34 -0700819 g.P(protoPackage.Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil993c04d2018-09-14 15:41:11 -0700820 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700821 g.P("}")
822 g.P()
823}
824
Damien Neil55fe1c02018-09-17 15:11:24 -0700825// deprecationComment returns a standard deprecation comment if deprecated is true.
826func deprecationComment(deprecated bool) string {
827 if !deprecated {
828 return ""
829 }
830 return "// Deprecated: Do not use."
831}
832
Damien Neilea7baf42018-09-28 14:23:44 -0700833func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700834 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700835 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700836 g.P()
837 }
838}
839
840// Names of messages and enums for which we will generate XXX_WellKnownType methods.
841var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700842 "google.protobuf.Any": true,
843 "google.protobuf.Duration": true,
844 "google.protobuf.Empty": true,
845 "google.protobuf.Struct": true,
846 "google.protobuf.Timestamp": true,
847
848 "google.protobuf.BoolValue": true,
849 "google.protobuf.BytesValue": true,
850 "google.protobuf.DoubleValue": true,
851 "google.protobuf.FloatValue": true,
852 "google.protobuf.Int32Value": true,
853 "google.protobuf.Int64Value": true,
854 "google.protobuf.ListValue": true,
855 "google.protobuf.NullValue": true,
856 "google.protobuf.StringValue": true,
857 "google.protobuf.UInt32Value": true,
858 "google.protobuf.UInt64Value": true,
859 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700860}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800861
862// genOneofField generates the struct field for a oneof.
863func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
864 if g.PrintLeadingComments(oneof.Location) {
865 g.P("//")
866 }
867 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
868 for _, field := range oneof.Fields {
869 g.PrintLeadingComments(field.Location)
870 g.P("//\t*", fieldOneofType(field))
871 }
872 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
873 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
874}
875
876// genOneofTypes generates the interface type used for a oneof field,
877// and the wrapper types that satisfy that interface.
878//
879// It also generates the getter method for the parent oneof field
880// (but not the member fields).
881func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
882 ifName := oneofInterfaceName(oneof)
883 g.P("type ", ifName, " interface {")
884 g.P(ifName, "()")
885 g.P("}")
886 g.P()
887 for _, field := range oneof.Fields {
888 name := fieldOneofType(field)
889 g.Annotate(name.GoName, field.Location)
890 g.Annotate(name.GoName+"."+field.GoName, field.Location)
891 g.P("type ", name, " struct {")
892 goType, _ := fieldGoType(g, field)
893 tags := []string{
894 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
895 }
896 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
897 g.P("}")
898 g.P()
899 }
900 for _, field := range oneof.Fields {
901 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
902 g.P()
903 }
904 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
905 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
906 g.P("if m != nil {")
907 g.P("return m.", oneofFieldName(oneof))
908 g.P("}")
909 g.P("return nil")
910 g.P("}")
911 g.P()
912}
913
914// oneofFieldName returns the name of the struct field holding the oneof value.
915//
916// This function is trivial, but pulling out the name like this makes it easier
917// to experiment with alternative oneof implementations.
918func oneofFieldName(oneof *protogen.Oneof) string {
919 return oneof.GoName
920}
921
922// oneofInterfaceName returns the name of the interface type implemented by
923// the oneof field value types.
924func oneofInterfaceName(oneof *protogen.Oneof) string {
925 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
926}
927
928// genOneofWrappers generates the XXX_OneofWrappers method for a message.
929func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
930 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
931 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
932 g.P("return []interface{}{")
933 for _, oneof := range message.Oneofs {
934 for _, field := range oneof.Fields {
935 g.P("(*", fieldOneofType(field), ")(nil),")
936 }
937 }
938 g.P("}")
939 g.P("}")
940 g.P()
941}
942
943// fieldOneofType returns the wrapper type used to represent a field in a oneof.
944func fieldOneofType(field *protogen.Field) protogen.GoIdent {
945 ident := protogen.GoIdent{
946 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
947 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
948 }
949 // Check for collisions with nested messages or enums.
950 //
951 // This conflict resolution is incomplete: Among other things, it
952 // does not consider collisions with other oneof field types.
953 //
954 // TODO: Consider dropping this entirely. Detecting conflicts and
955 // producing an error is almost certainly better than permuting
956 // field and type names in mostly unpredictable ways.
957Loop:
958 for {
959 for _, message := range field.ParentMessage.Messages {
960 if message.GoIdent == ident {
961 ident.GoName += "_"
962 continue Loop
963 }
964 }
965 for _, enum := range field.ParentMessage.Enums {
966 if enum.GoIdent == ident {
967 ident.GoName += "_"
968 continue Loop
969 }
970 }
971 return ident
972 }
973}