blob: b305819394ddbf2b808c4b8acf531ba45b47d347 [file] [log] [blame]
Damien Neil220c2022018-08-15 11:24:18 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Damien Neil1adaec92018-09-24 13:43:03 -07005// Package internal_gengo is internal to the protobuf module.
6package internal_gengo
Damien Neil220c2022018-08-15 11:24:18 -07007
8import (
Damien Neil7779e052018-09-07 14:14:06 -07009 "bytes"
10 "compress/gzip"
11 "crypto/sha256"
12 "encoding/hex"
13 "fmt"
Damien Neilebc699d2018-09-13 08:50:13 -070014 "math"
Damien Neilce36f8d2018-09-13 15:19:08 -070015 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070016 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070017 "strings"
Damien Neil7779e052018-09-07 14:14:06 -070018
19 "github.com/golang/protobuf/proto"
20 descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
Joe Tsai05828db2018-11-01 13:52:16 -070021 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai01ab2962018-09-21 17:44:00 -070022 "github.com/golang/protobuf/v2/protogen"
23 "github.com/golang/protobuf/v2/reflect/protoreflect"
Damien Neil220c2022018-08-15 11:24:18 -070024)
25
Damien Neild4127922018-09-12 11:13:49 -070026// generatedCodeVersion indicates a version of the generated code.
27// It is incremented whenever an incompatibility between the generated code and
28// proto package is introduced; the generated code references
29// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
Joe Tsaid7e97bc2018-11-26 12:57:27 -080030const generatedCodeVersion = 3
Damien Neild4127922018-09-12 11:13:49 -070031
Joe Tsaic1c17aa2018-11-16 11:14:14 -080032const (
33 fmtPackage = protogen.GoImportPath("fmt")
34 mathPackage = protogen.GoImportPath("math")
35 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
36)
Damien Neil46abb572018-09-07 12:45:37 -070037
Damien Neild39efc82018-09-24 12:38:10 -070038type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070039 *protogen.File
Damien Neil46abb572018-09-07 12:45:37 -070040 descriptorVar string // var containing the gzipped FileDescriptorProto
Damien Neilce36f8d2018-09-13 15:19:08 -070041 allEnums []*protogen.Enum
42 allMessages []*protogen.Message
Damien Neil993c04d2018-09-14 15:41:11 -070043 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070044}
45
Damien Neil9c420a62018-09-27 15:26:33 -070046// GenerateFile generates the contents of a .pb.go file.
47func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070048 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070049 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070050 }
51
Damien Neil993c04d2018-09-14 15:41:11 -070052 // The different order for enums and extensions is to match the output
53 // of the previous implementation.
54 //
55 // TODO: Eventually make this consistent.
Damien Neilce36f8d2018-09-13 15:19:08 -070056 f.allEnums = append(f.allEnums, f.File.Enums...)
Damien Neil73ac8852018-09-17 15:11:24 -070057 walkMessages(f.Messages, func(message *protogen.Message) {
58 f.allMessages = append(f.allMessages, message)
59 f.allEnums = append(f.allEnums, message.Enums...)
60 f.allExtensions = append(f.allExtensions, message.Extensions...)
61 })
Damien Neil993c04d2018-09-14 15:41:11 -070062 f.allExtensions = append(f.allExtensions, f.File.Extensions...)
Damien Neilce36f8d2018-09-13 15:19:08 -070063
Damien Neil46abb572018-09-07 12:45:37 -070064 // Determine the name of the var holding the file descriptor:
65 //
66 // fileDescriptor_<hash of filename>
67 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
68 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
69
Damien Neil220c2022018-08-15 11:24:18 -070070 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070071 if f.Proto.GetOptions().GetDeprecated() {
72 g.P("// ", f.Desc.Path(), " is a deprecated file.")
73 } else {
74 g.P("// source: ", f.Desc.Path())
75 }
Damien Neil220c2022018-08-15 11:24:18 -070076 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070077 const filePackageField = 2 // FileDescriptorProto.package
Damien Neilba1159f2018-10-17 12:53:18 -070078 g.PrintLeadingComments(protogen.Location{
79 SourceFile: f.Proto.GetName(),
80 Path: []int32{filePackageField},
81 })
Damien Neilcab8dfe2018-09-06 14:51:28 -070082 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070083 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070084 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -070085
86 // These references are not necessary, since we automatically add
87 // all necessary imports before formatting the generated file.
88 //
89 // This section exists to generate output more consistent with
90 // the previous version of protoc-gen-go, to make it easier to
91 // detect unintended variations.
92 //
93 // TODO: Eventually remove this.
94 g.P("// Reference imports to suppress errors if they are not otherwise used.")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080095 g.P("var _ = ", protoPackage.Ident("Marshal"))
96 g.P("var _ = ", fmtPackage.Ident("Errorf"))
97 g.P("var _ = ", mathPackage.Ident("Inf"))
Damien Neil1ec33152018-09-13 13:12:36 -070098 g.P()
99
Damien Neild4127922018-09-12 11:13:49 -0700100 g.P("// This is a compile-time assertion to ensure that this generated file")
101 g.P("// is compatible with the proto package it is being compiled against.")
102 g.P("// A compilation error at this line likely means your copy of the")
103 g.P("// proto package needs to be updated.")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800104 g.P("const _ = ", protoPackage.Ident(fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion)),
105 "// please upgrade the proto package")
Damien Neild4127922018-09-12 11:13:49 -0700106 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700107
Damien Neil73ac8852018-09-17 15:11:24 -0700108 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
109 genImport(gen, g, f, imps.Get(i))
110 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700111 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700112 genEnum(gen, g, f, enum)
113 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700114 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700115 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700116 }
Damien Neil993c04d2018-09-14 15:41:11 -0700117 for _, extension := range f.Extensions {
118 genExtension(gen, g, f, extension)
119 }
Damien Neil220c2022018-08-15 11:24:18 -0700120
Damien Neilce36f8d2018-09-13 15:19:08 -0700121 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700122 genFileDescriptor(gen, g, f)
123}
124
Damien Neil73ac8852018-09-17 15:11:24 -0700125// walkMessages calls f on each message and all of its descendants.
126func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
127 for _, m := range messages {
128 f(m)
129 walkMessages(m.Messages, f)
130 }
131}
132
Damien Neild39efc82018-09-24 12:38:10 -0700133func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700134 impFile, ok := gen.FileByName(imp.Path())
135 if !ok {
136 return
137 }
138 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700139 // Don't generate imports or aliases for types in the same Go package.
140 return
141 }
Damien Neil40a08052018-10-29 09:07:41 -0700142 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700143 // referenced, because other code and tools depend on having the
144 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700145 if !imp.IsWeak {
146 g.Import(impFile.GoImportPath)
147 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700148 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700149 return
150 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700151 // TODO: An alternate approach to generating public imports might be
152 // to generate the imported file contents, parse it, and extract all
153 // exported identifiers from the AST to build a list of forwarding
154 // declarations.
155 //
156 // TODO: Consider whether this should generate recursive aliases. e.g.,
157 // if a.proto publicly imports b.proto publicly imports c.proto, should
158 // a.pb.go contain aliases for symbols defined in c.proto?
Damien Neil73ac8852018-09-17 15:11:24 -0700159 var enums []*protogen.Enum
160 enums = append(enums, impFile.Enums...)
161 walkMessages(impFile.Messages, func(message *protogen.Message) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700162 if message.Desc.IsMapEntry() {
163 return
164 }
Damien Neil73ac8852018-09-17 15:11:24 -0700165 enums = append(enums, message.Enums...)
Damien Neil2193e8d2018-10-09 12:49:13 -0700166 for _, field := range message.Fields {
167 if !fieldHasDefault(field) {
168 continue
169 }
170 defVar := protogen.GoIdent{
171 GoImportPath: message.GoIdent.GoImportPath,
172 GoName: "Default_" + message.GoIdent.GoName + "_" + field.GoName,
173 }
174 decl := "const"
175 if field.Desc.Kind() == protoreflect.BytesKind {
176 decl = "var"
177 }
178 g.P(decl, " ", defVar.GoName, " = ", defVar)
179 }
Damien Neil73ac8852018-09-17 15:11:24 -0700180 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
181 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
182 for _, oneof := range message.Oneofs {
183 for _, field := range oneof.Fields {
184 typ := fieldOneofType(field)
185 g.P("type ", typ.GoName, " = ", typ)
186 }
187 }
188 g.P()
189 })
190 for _, enum := range enums {
191 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
192 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
193 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
194 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
195 g.P()
196 for _, value := range enum.Values {
197 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
198 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700199 }
Damien Neil6b541312018-10-29 09:14:14 -0700200 for _, ext := range impFile.Extensions {
201 ident := extensionVar(impFile, ext)
202 g.P("var ", ident.GoName, " = ", ident)
203 g.P()
204 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700205 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700206}
207
Damien Neild39efc82018-09-24 12:38:10 -0700208func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700209 // Trim the source_code_info from the descriptor.
210 // Marshal and gzip it.
211 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
212 descProto.SourceCodeInfo = nil
213 b, err := proto.Marshal(descProto)
214 if err != nil {
215 gen.Error(err)
216 return
217 }
218 var buf bytes.Buffer
219 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
220 w.Write(b)
221 w.Close()
222 b = buf.Bytes()
223
Damien Neil46abb572018-09-07 12:45:37 -0700224 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700225 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700226 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700227 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
228 for len(b) > 0 {
229 n := 16
230 if n > len(b) {
231 n = len(b)
232 }
233
234 s := ""
235 for _, c := range b[:n] {
236 s += fmt.Sprintf("0x%02x,", c)
237 }
238 g.P(s)
239
240 b = b[n:]
241 }
242 g.P("}")
243 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700244}
Damien Neilc7d07d92018-08-22 13:46:02 -0700245
Damien Neild39efc82018-09-24 12:38:10 -0700246func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700247 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700248 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700249 g.P("type ", enum.GoIdent, " int32",
Damien Neil204f1c02018-10-23 15:03:38 -0700250 deprecationComment(enum.Desc.Options().(*descpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700251 g.P("const (")
252 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700253 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700254 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700255 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Damien Neil204f1c02018-10-23 15:03:38 -0700256 deprecationComment(value.Desc.Options().(*descpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700257 }
258 g.P(")")
259 g.P()
260 nameMap := enum.GoIdent.GoName + "_name"
261 g.P("var ", nameMap, " = map[int32]string{")
262 generated := make(map[protoreflect.EnumNumber]bool)
263 for _, value := range enum.Values {
264 duplicate := ""
265 if _, present := generated[value.Desc.Number()]; present {
266 duplicate = "// Duplicate value: "
267 }
268 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
269 generated[value.Desc.Number()] = true
270 }
271 g.P("}")
272 g.P()
273 valueMap := enum.GoIdent.GoName + "_value"
274 g.P("var ", valueMap, " = map[string]int32{")
275 for _, value := range enum.Values {
276 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
277 }
278 g.P("}")
279 g.P()
280 if enum.Desc.Syntax() != protoreflect.Proto3 {
281 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
282 g.P("p := new(", enum.GoIdent, ")")
283 g.P("*p = x")
284 g.P("return p")
285 g.P("}")
286 g.P()
287 }
288 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800289 g.P("return ", protoPackage.Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700290 g.P("}")
291 g.P()
292
293 if enum.Desc.Syntax() != protoreflect.Proto3 {
294 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800295 g.P("value, err := ", protoPackage.Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700296 g.P("if err != nil {")
297 g.P("return err")
298 g.P("}")
299 g.P("*x = ", enum.GoIdent, "(value)")
300 g.P("return nil")
301 g.P("}")
302 g.P()
303 }
304
305 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700306 for i := 1; i < len(enum.Location.Path); i += 2 {
307 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700308 }
309 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
310 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
311 g.P("}")
312 g.P()
313
Damien Neilea7baf42018-09-28 14:23:44 -0700314 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700315}
316
Damien Neil658051b2018-09-10 12:26:21 -0700317// enumRegistryName returns the name used to register an enum with the proto
318// package registry.
319//
320// Confusingly, this is <proto_package>.<go_ident>. This probably should have
321// been the full name of the proto enum type instead, but changing it at this
322// point would require thought.
323func enumRegistryName(enum *protogen.Enum) string {
324 // Find the FileDescriptor for this enum.
325 var desc protoreflect.Descriptor = enum.Desc
326 for {
327 p, ok := desc.Parent()
328 if !ok {
329 break
330 }
331 desc = p
332 }
333 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700334 if fdesc.Package() == "" {
335 return enum.GoIdent.GoName
336 }
Damien Neil658051b2018-09-10 12:26:21 -0700337 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
338}
339
Damien Neild39efc82018-09-24 12:38:10 -0700340func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700341 if message.Desc.IsMapEntry() {
342 return
343 }
344
Damien Neilba1159f2018-10-17 12:53:18 -0700345 hasComment := g.PrintLeadingComments(message.Location)
Damien Neil204f1c02018-10-23 15:03:38 -0700346 if message.Desc.Options().(*descpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700347 if hasComment {
348 g.P("//")
349 }
350 g.P(deprecationComment(true))
351 }
Damien Neil162c1272018-10-04 12:42:37 -0700352 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700353 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700354 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700355 if field.OneofType != nil {
356 // It would be a bit simpler to iterate over the oneofs below,
357 // but generating the field here keeps the contents of the Go
358 // struct in the same order as the contents of the source
359 // .proto file.
360 if field == field.OneofType.Fields[0] {
361 genOneofField(gen, g, f, message, field.OneofType)
362 }
Damien Neil658051b2018-09-10 12:26:21 -0700363 continue
364 }
Damien Neilba1159f2018-10-17 12:53:18 -0700365 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700366 goType, pointer := fieldGoType(g, field)
367 if pointer {
368 goType = "*" + goType
369 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700370 tags := []string{
371 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
372 fmt.Sprintf("json:%q", fieldJSONTag(field)),
373 }
374 if field.Desc.IsMap() {
375 key := field.MessageType.Fields[0]
376 val := field.MessageType.Fields[1]
377 tags = append(tags,
378 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
379 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
380 )
381 }
Damien Neil162c1272018-10-04 12:42:37 -0700382 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700383 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Damien Neil204f1c02018-10-23 15:03:38 -0700384 deprecationComment(field.Desc.Options().(*descpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700385 }
386 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700387
388 if message.Desc.ExtensionRanges().Len() > 0 {
389 var tags []string
Damien Neil204f1c02018-10-23 15:03:38 -0700390 if message.Desc.Options().(*descpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700391 tags = append(tags, `protobuf_messageset:"1"`)
392 }
393 tags = append(tags, `json:"-"`)
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800394 g.P(protoPackage.Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700395 }
Damien Neil658051b2018-09-10 12:26:21 -0700396 // TODO XXX_InternalExtensions
397 g.P("XXX_unrecognized []byte `json:\"-\"`")
398 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700399 g.P("}")
400 g.P()
401
Damien Neila1c6abc2018-09-12 13:36:34 -0700402 // Reset
403 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
404 // String
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800405 g.P("func (m *", message.GoIdent, ") String() string { return ", protoPackage.Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700406 // ProtoMessage
407 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
408 // Descriptor
409 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700410 for i := 1; i < len(message.Location.Path); i += 2 {
411 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700412 }
413 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
414 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
415 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700416 g.P()
417
418 // ExtensionRangeArray
419 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800420 protoExtRange := protoPackage.Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700421 extRangeVar := "extRange_" + message.GoIdent.GoName
422 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
423 for i := 0; i < extranges.Len(); i++ {
424 r := extranges.Get(i)
425 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
426 }
427 g.P("}")
428 g.P()
429 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
430 g.P("return ", extRangeVar)
431 g.P("}")
432 g.P()
433 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700434
Damien Neilea7baf42018-09-28 14:23:44 -0700435 genWellKnownType(g, "*", message.GoIdent, message.Desc)
436
Damien Neila1c6abc2018-09-12 13:36:34 -0700437 // Table-driven proto support.
438 //
439 // TODO: It does not scale to keep adding another method for every
440 // operation on protos that we want to switch over to using the
441 // table-driven approach. Instead, we should only add a single method
442 // that allows getting access to the *InternalMessageInfo struct and then
443 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
444 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
445 // XXX_Unmarshal
446 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
447 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
448 g.P("}")
449 // XXX_Marshal
450 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
451 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
452 g.P("}")
453 // XXX_Merge
454 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
455 g.P(messageInfoVar, ".Merge(m, src)")
456 g.P("}")
457 // XXX_Size
458 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
459 g.P("return ", messageInfoVar, ".Size(m)")
460 g.P("}")
461 // XXX_DiscardUnknown
462 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
463 g.P(messageInfoVar, ".DiscardUnknown(m)")
464 g.P("}")
465 g.P()
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800466 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
Damien Neila1c6abc2018-09-12 13:36:34 -0700467 g.P()
468
Damien Neilebc699d2018-09-13 08:50:13 -0700469 // Constants and vars holding the default values of fields.
470 for _, field := range message.Fields {
Damien Neilccf3fa62018-09-28 14:41:45 -0700471 if !fieldHasDefault(field) {
Damien Neilebc699d2018-09-13 08:50:13 -0700472 continue
473 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700474 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700475 def := field.Desc.Default()
476 switch field.Desc.Kind() {
477 case protoreflect.StringKind:
478 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
479 case protoreflect.BytesKind:
480 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
481 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700482 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700483 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700484 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700485 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
486 case protoreflect.FloatKind, protoreflect.DoubleKind:
487 // Floating point numbers need extra handling for -Inf/Inf/NaN.
488 f := field.Desc.Default().Float()
489 goType := "float64"
490 if field.Desc.Kind() == protoreflect.FloatKind {
491 goType = "float32"
492 }
493 // funcCall returns a call to a function in the math package,
494 // possibly converting the result to float32.
495 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800496 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700497 if goType != "float64" {
498 s = goType + "(" + s + ")"
499 }
500 return s
501 }
502 switch {
503 case math.IsInf(f, -1):
504 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
505 case math.IsInf(f, 1):
506 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
507 case math.IsNaN(f):
508 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
509 default:
Damien Neil982684b2018-09-28 14:12:41 -0700510 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700511 }
512 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700513 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700514 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
515 }
516 }
517 g.P()
518
Damien Neil77f82fe2018-09-13 10:59:17 -0700519 // Getters.
520 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700521 if field.OneofType != nil {
522 if field == field.OneofType.Fields[0] {
523 genOneofTypes(gen, g, f, message, field.OneofType)
524 }
525 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700526 goType, pointer := fieldGoType(g, field)
527 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil204f1c02018-10-23 15:03:38 -0700528 if field.Desc.Options().(*descpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700529 g.P(deprecationComment(true))
530 }
Damien Neil162c1272018-10-04 12:42:37 -0700531 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700532 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
533 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700534 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700535 g.P("return x.", field.GoName)
536 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700537 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700538 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
539 g.P("if m != nil {")
540 } else {
541 g.P("if m != nil && m.", field.GoName, " != nil {")
542 }
543 star := ""
544 if pointer {
545 star = "*"
546 }
547 g.P("return ", star, " m.", field.GoName)
548 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700549 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700550 g.P("return ", defaultValue)
551 g.P("}")
552 g.P()
553 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700554
Damien Neil1fa78d82018-09-13 13:12:36 -0700555 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800556 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700557 }
Damien Neil993c04d2018-09-14 15:41:11 -0700558 for _, extension := range message.Extensions {
559 genExtension(gen, g, f, extension)
560 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700561}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700562
Damien Neil77f82fe2018-09-13 10:59:17 -0700563// fieldGoType returns the Go type used for a field.
564//
565// If it returns pointer=true, the struct field is a pointer to the type.
566func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700567 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700568 switch field.Desc.Kind() {
569 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700570 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700571 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700572 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700573 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700574 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700575 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700576 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700577 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700578 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700579 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700580 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700581 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700582 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700583 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700584 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700585 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700586 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700587 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700588 goType = "[]byte"
589 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700590 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700591 if field.Desc.IsMap() {
592 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
593 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
594 return fmt.Sprintf("map[%v]%v", keyType, valType), false
595 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700596 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
597 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700598 }
599 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700600 goType = "[]" + goType
601 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700602 }
Damien Neil44000a12018-10-24 12:31:16 -0700603 // Extension fields always have pointer type, even when defined in a proto3 file.
604 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700605 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700606 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700607 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700608}
609
610func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700611 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700612 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700613 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700614 }
Joe Tsai05828db2018-11-01 13:52:16 -0700615 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700616}
617
Damien Neil77f82fe2018-09-13 10:59:17 -0700618func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
619 if field.Desc.Cardinality() == protoreflect.Repeated {
620 return "nil"
621 }
Damien Neilccf3fa62018-09-28 14:41:45 -0700622 if fieldHasDefault(field) {
Damien Neil1fa78d82018-09-13 13:12:36 -0700623 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 if field.Desc.Kind() == protoreflect.BytesKind {
625 return "append([]byte(nil), " + defVarName + "...)"
626 }
627 return defVarName
628 }
629 switch field.Desc.Kind() {
630 case protoreflect.BoolKind:
631 return "false"
632 case protoreflect.StringKind:
633 return `""`
634 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
635 return "nil"
636 case protoreflect.EnumKind:
637 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
638 default:
639 return "0"
640 }
641}
642
Damien Neilccf3fa62018-09-28 14:41:45 -0700643// fieldHasDefault returns true if we consider a field to have a default value.
644//
645// For consistency with the previous generator, it returns false for fields with
646// [default=""], preventing the generation of a default const or var for these
647// fields.
648//
649// TODO: Drop this special case.
650func fieldHasDefault(field *protogen.Field) bool {
651 if !field.Desc.HasDefault() {
652 return false
653 }
654 switch field.Desc.Kind() {
655 case protoreflect.StringKind:
656 return field.Desc.Default().String() != ""
657 case protoreflect.BytesKind:
658 return len(field.Desc.Default().Bytes()) > 0
659 }
660 return true
661}
662
Damien Neil658051b2018-09-10 12:26:21 -0700663func fieldJSONTag(field *protogen.Field) string {
664 return string(field.Desc.Name()) + ",omitempty"
665}
666
Damien Neild39efc82018-09-24 12:38:10 -0700667func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700668 // Special case for proto2 message sets: If this extension is extending
669 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
670 // then drop that last component.
671 //
672 // TODO: This should be implemented in the text formatter rather than the generator.
673 // In addition, the situation for when to apply this special case is implemented
674 // differently in other languages:
675 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
676 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700677 if n, ok := isExtensionMessageSetElement(extension); ok {
678 name = n
Damien Neil154da982018-09-19 13:21:58 -0700679 }
680
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800681 g.P("var ", extensionVar(f.File, extension), " = &", protoPackage.Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700682 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
683 goType, pointer := fieldGoType(g, extension)
684 if pointer {
685 goType = "*" + goType
686 }
687 g.P("ExtensionType: (", goType, ")(nil),")
688 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700689 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700690 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
691 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
692 g.P("}")
693 g.P()
694}
695
Damien Neil62386962018-10-30 10:35:48 -0700696// isExtensionMessageSetELement returns the adjusted name of an extension
697// which extends proto2.bridge.MessageSet.
698func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
699 opts := extension.ExtendedType.Desc.Options().(*descpb.MessageOptions)
700 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
701 return "", false
702 }
703 if extension.ParentMessage == nil {
704 // This case shouldn't be given special handling at all--we're
705 // only supposed to drop the ".message_set_extension" for
706 // extensions defined within a message (i.e., the extension
707 // takes the message's name).
708 //
709 // This matches the behavior of the v1 generator, however.
710 //
711 // TODO: See if we can drop this case.
712 name = extension.Desc.FullName()
713 name = name[:len(name)-len("message_set_extension")]
714 return name, true
715 }
716 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700717}
718
Damien Neil993c04d2018-09-14 15:41:11 -0700719// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700720func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700721 name := "E_"
722 if extension.ParentMessage != nil {
723 name += extension.ParentMessage.GoIdent.GoName + "_"
724 }
725 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800726 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700727}
728
Damien Neilce36f8d2018-09-13 15:19:08 -0700729// genInitFunction generates an init function that registers the types in the
730// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700731func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil993c04d2018-09-14 15:41:11 -0700732 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700733 return
734 }
735
736 g.P("func init() {")
Damien Neil154da982018-09-19 13:21:58 -0700737 for _, enum := range f.allEnums {
738 name := enum.GoIdent.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800739 g.P(protoPackage.Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700740 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700741 for _, message := range f.allMessages {
742 if message.Desc.IsMapEntry() {
743 continue
744 }
745
Damien Neil154da982018-09-19 13:21:58 -0700746 for _, extension := range message.Extensions {
747 genRegisterExtension(gen, g, f, extension)
748 }
749
Damien Neilce36f8d2018-09-13 15:19:08 -0700750 name := message.GoIdent.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800751 g.P(protoPackage.Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700752
753 // Types of map fields, sorted by the name of the field message type.
754 var mapFields []*protogen.Field
755 for _, field := range message.Fields {
756 if field.Desc.IsMap() {
757 mapFields = append(mapFields, field)
758 }
759 }
760 sort.Slice(mapFields, func(i, j int) bool {
761 ni := mapFields[i].MessageType.Desc.FullName()
762 nj := mapFields[j].MessageType.Desc.FullName()
763 return ni < nj
764 })
765 for _, field := range mapFields {
766 typeName := string(field.MessageType.Desc.FullName())
767 goType, _ := fieldGoType(g, field)
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800768 g.P(protoPackage.Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700769 }
770 }
Damien Neil154da982018-09-19 13:21:58 -0700771 for _, extension := range f.Extensions {
772 genRegisterExtension(gen, g, f, extension)
Damien Neil993c04d2018-09-14 15:41:11 -0700773 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700774 g.P("}")
775 g.P()
776}
777
Damien Neild39efc82018-09-24 12:38:10 -0700778func genRegisterExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800779 g.P(protoPackage.Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil154da982018-09-19 13:21:58 -0700780}
781
Damien Neil55fe1c02018-09-17 15:11:24 -0700782// deprecationComment returns a standard deprecation comment if deprecated is true.
783func deprecationComment(deprecated bool) string {
784 if !deprecated {
785 return ""
786 }
787 return "// Deprecated: Do not use."
788}
789
Damien Neilea7baf42018-09-28 14:23:44 -0700790func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700791 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700792 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700793 g.P()
794 }
795}
796
797// Names of messages and enums for which we will generate XXX_WellKnownType methods.
798var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700799 "google.protobuf.Any": true,
800 "google.protobuf.Duration": true,
801 "google.protobuf.Empty": true,
802 "google.protobuf.Struct": true,
803 "google.protobuf.Timestamp": true,
804
805 "google.protobuf.BoolValue": true,
806 "google.protobuf.BytesValue": true,
807 "google.protobuf.DoubleValue": true,
808 "google.protobuf.FloatValue": true,
809 "google.protobuf.Int32Value": true,
810 "google.protobuf.Int64Value": true,
811 "google.protobuf.ListValue": true,
812 "google.protobuf.NullValue": true,
813 "google.protobuf.StringValue": true,
814 "google.protobuf.UInt32Value": true,
815 "google.protobuf.UInt64Value": true,
816 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700817}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800818
819// genOneofField generates the struct field for a oneof.
820func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
821 if g.PrintLeadingComments(oneof.Location) {
822 g.P("//")
823 }
824 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
825 for _, field := range oneof.Fields {
826 g.PrintLeadingComments(field.Location)
827 g.P("//\t*", fieldOneofType(field))
828 }
829 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
830 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
831}
832
833// genOneofTypes generates the interface type used for a oneof field,
834// and the wrapper types that satisfy that interface.
835//
836// It also generates the getter method for the parent oneof field
837// (but not the member fields).
838func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
839 ifName := oneofInterfaceName(oneof)
840 g.P("type ", ifName, " interface {")
841 g.P(ifName, "()")
842 g.P("}")
843 g.P()
844 for _, field := range oneof.Fields {
845 name := fieldOneofType(field)
846 g.Annotate(name.GoName, field.Location)
847 g.Annotate(name.GoName+"."+field.GoName, field.Location)
848 g.P("type ", name, " struct {")
849 goType, _ := fieldGoType(g, field)
850 tags := []string{
851 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
852 }
853 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
854 g.P("}")
855 g.P()
856 }
857 for _, field := range oneof.Fields {
858 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
859 g.P()
860 }
861 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
862 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
863 g.P("if m != nil {")
864 g.P("return m.", oneofFieldName(oneof))
865 g.P("}")
866 g.P("return nil")
867 g.P("}")
868 g.P()
869}
870
871// oneofFieldName returns the name of the struct field holding the oneof value.
872//
873// This function is trivial, but pulling out the name like this makes it easier
874// to experiment with alternative oneof implementations.
875func oneofFieldName(oneof *protogen.Oneof) string {
876 return oneof.GoName
877}
878
879// oneofInterfaceName returns the name of the interface type implemented by
880// the oneof field value types.
881func oneofInterfaceName(oneof *protogen.Oneof) string {
882 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
883}
884
885// genOneofWrappers generates the XXX_OneofWrappers method for a message.
886func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
887 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
888 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
889 g.P("return []interface{}{")
890 for _, oneof := range message.Oneofs {
891 for _, field := range oneof.Fields {
892 g.P("(*", fieldOneofType(field), ")(nil),")
893 }
894 }
895 g.P("}")
896 g.P("}")
897 g.P()
898}
899
900// fieldOneofType returns the wrapper type used to represent a field in a oneof.
901func fieldOneofType(field *protogen.Field) protogen.GoIdent {
902 ident := protogen.GoIdent{
903 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
904 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
905 }
906 // Check for collisions with nested messages or enums.
907 //
908 // This conflict resolution is incomplete: Among other things, it
909 // does not consider collisions with other oneof field types.
910 //
911 // TODO: Consider dropping this entirely. Detecting conflicts and
912 // producing an error is almost certainly better than permuting
913 // field and type names in mostly unpredictable ways.
914Loop:
915 for {
916 for _, message := range field.ParentMessage.Messages {
917 if message.GoIdent == ident {
918 ident.GoName += "_"
919 continue Loop
920 }
921 }
922 for _, enum := range field.ParentMessage.Enums {
923 if enum.GoIdent == ident {
924 ident.GoName += "_"
925 continue Loop
926 }
927 }
928 return ident
929 }
930}