blob: 53d6458015a0e4dd374a8c2dee1f49f61db806a0 [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"
Damien Neil7e5c6472018-11-29 08:57:07 -0800175 switch field.Desc.Kind() {
176 case protoreflect.BytesKind:
Damien Neil2193e8d2018-10-09 12:49:13 -0700177 decl = "var"
Damien Neil7e5c6472018-11-29 08:57:07 -0800178 case protoreflect.FloatKind, protoreflect.DoubleKind:
179 f := field.Desc.Default().Float()
180 if math.IsInf(f, -1) || math.IsInf(f, 1) || math.IsNaN(f) {
181 decl = "var"
182 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700183 }
184 g.P(decl, " ", defVar.GoName, " = ", defVar)
185 }
Damien Neil73ac8852018-09-17 15:11:24 -0700186 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
187 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
188 for _, oneof := range message.Oneofs {
189 for _, field := range oneof.Fields {
190 typ := fieldOneofType(field)
191 g.P("type ", typ.GoName, " = ", typ)
192 }
193 }
194 g.P()
195 })
196 for _, enum := range enums {
197 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
198 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
199 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
200 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
201 g.P()
202 for _, value := range enum.Values {
203 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
204 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700205 }
Damien Neil6b541312018-10-29 09:14:14 -0700206 for _, ext := range impFile.Extensions {
207 ident := extensionVar(impFile, ext)
208 g.P("var ", ident.GoName, " = ", ident)
209 g.P()
210 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700211 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700212}
213
Damien Neild39efc82018-09-24 12:38:10 -0700214func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700215 // Trim the source_code_info from the descriptor.
216 // Marshal and gzip it.
217 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
218 descProto.SourceCodeInfo = nil
219 b, err := proto.Marshal(descProto)
220 if err != nil {
221 gen.Error(err)
222 return
223 }
224 var buf bytes.Buffer
225 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
226 w.Write(b)
227 w.Close()
228 b = buf.Bytes()
229
Damien Neil46abb572018-09-07 12:45:37 -0700230 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700231 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700232 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700233 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
234 for len(b) > 0 {
235 n := 16
236 if n > len(b) {
237 n = len(b)
238 }
239
240 s := ""
241 for _, c := range b[:n] {
242 s += fmt.Sprintf("0x%02x,", c)
243 }
244 g.P(s)
245
246 b = b[n:]
247 }
248 g.P("}")
249 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700250}
Damien Neilc7d07d92018-08-22 13:46:02 -0700251
Damien Neild39efc82018-09-24 12:38:10 -0700252func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700253 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700254 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700255 g.P("type ", enum.GoIdent, " int32",
Damien Neil204f1c02018-10-23 15:03:38 -0700256 deprecationComment(enum.Desc.Options().(*descpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700257 g.P("const (")
258 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700259 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700260 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700261 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Damien Neil204f1c02018-10-23 15:03:38 -0700262 deprecationComment(value.Desc.Options().(*descpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700263 }
264 g.P(")")
265 g.P()
266 nameMap := enum.GoIdent.GoName + "_name"
267 g.P("var ", nameMap, " = map[int32]string{")
268 generated := make(map[protoreflect.EnumNumber]bool)
269 for _, value := range enum.Values {
270 duplicate := ""
271 if _, present := generated[value.Desc.Number()]; present {
272 duplicate = "// Duplicate value: "
273 }
274 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
275 generated[value.Desc.Number()] = true
276 }
277 g.P("}")
278 g.P()
279 valueMap := enum.GoIdent.GoName + "_value"
280 g.P("var ", valueMap, " = map[string]int32{")
281 for _, value := range enum.Values {
282 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
283 }
284 g.P("}")
285 g.P()
286 if enum.Desc.Syntax() != protoreflect.Proto3 {
287 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
288 g.P("p := new(", enum.GoIdent, ")")
289 g.P("*p = x")
290 g.P("return p")
291 g.P("}")
292 g.P()
293 }
294 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800295 g.P("return ", protoPackage.Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700296 g.P("}")
297 g.P()
298
299 if enum.Desc.Syntax() != protoreflect.Proto3 {
300 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800301 g.P("value, err := ", protoPackage.Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700302 g.P("if err != nil {")
303 g.P("return err")
304 g.P("}")
305 g.P("*x = ", enum.GoIdent, "(value)")
306 g.P("return nil")
307 g.P("}")
308 g.P()
309 }
310
311 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700312 for i := 1; i < len(enum.Location.Path); i += 2 {
313 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700314 }
315 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
316 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
317 g.P("}")
318 g.P()
319
Damien Neilea7baf42018-09-28 14:23:44 -0700320 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700321}
322
Damien Neil658051b2018-09-10 12:26:21 -0700323// enumRegistryName returns the name used to register an enum with the proto
324// package registry.
325//
326// Confusingly, this is <proto_package>.<go_ident>. This probably should have
327// been the full name of the proto enum type instead, but changing it at this
328// point would require thought.
329func enumRegistryName(enum *protogen.Enum) string {
330 // Find the FileDescriptor for this enum.
331 var desc protoreflect.Descriptor = enum.Desc
332 for {
333 p, ok := desc.Parent()
334 if !ok {
335 break
336 }
337 desc = p
338 }
339 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700340 if fdesc.Package() == "" {
341 return enum.GoIdent.GoName
342 }
Damien Neil658051b2018-09-10 12:26:21 -0700343 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
344}
345
Damien Neild39efc82018-09-24 12:38:10 -0700346func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700347 if message.Desc.IsMapEntry() {
348 return
349 }
350
Damien Neilba1159f2018-10-17 12:53:18 -0700351 hasComment := g.PrintLeadingComments(message.Location)
Damien Neil204f1c02018-10-23 15:03:38 -0700352 if message.Desc.Options().(*descpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700353 if hasComment {
354 g.P("//")
355 }
356 g.P(deprecationComment(true))
357 }
Damien Neil162c1272018-10-04 12:42:37 -0700358 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700359 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700360 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700361 if field.OneofType != nil {
362 // It would be a bit simpler to iterate over the oneofs below,
363 // but generating the field here keeps the contents of the Go
364 // struct in the same order as the contents of the source
365 // .proto file.
366 if field == field.OneofType.Fields[0] {
367 genOneofField(gen, g, f, message, field.OneofType)
368 }
Damien Neil658051b2018-09-10 12:26:21 -0700369 continue
370 }
Damien Neilba1159f2018-10-17 12:53:18 -0700371 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700372 goType, pointer := fieldGoType(g, field)
373 if pointer {
374 goType = "*" + goType
375 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700376 tags := []string{
377 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
378 fmt.Sprintf("json:%q", fieldJSONTag(field)),
379 }
380 if field.Desc.IsMap() {
381 key := field.MessageType.Fields[0]
382 val := field.MessageType.Fields[1]
383 tags = append(tags,
384 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
385 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
386 )
387 }
Damien Neil162c1272018-10-04 12:42:37 -0700388 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700389 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Damien Neil204f1c02018-10-23 15:03:38 -0700390 deprecationComment(field.Desc.Options().(*descpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700391 }
392 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700393
394 if message.Desc.ExtensionRanges().Len() > 0 {
395 var tags []string
Damien Neil204f1c02018-10-23 15:03:38 -0700396 if message.Desc.Options().(*descpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700397 tags = append(tags, `protobuf_messageset:"1"`)
398 }
399 tags = append(tags, `json:"-"`)
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800400 g.P(protoPackage.Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700401 }
Damien Neil658051b2018-09-10 12:26:21 -0700402 // TODO XXX_InternalExtensions
403 g.P("XXX_unrecognized []byte `json:\"-\"`")
404 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700405 g.P("}")
406 g.P()
407
Damien Neila1c6abc2018-09-12 13:36:34 -0700408 // Reset
409 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
410 // String
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800411 g.P("func (m *", message.GoIdent, ") String() string { return ", protoPackage.Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700412 // ProtoMessage
413 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
414 // Descriptor
415 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700416 for i := 1; i < len(message.Location.Path); i += 2 {
417 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700418 }
419 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
420 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
421 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700422 g.P()
423
424 // ExtensionRangeArray
425 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800426 protoExtRange := protoPackage.Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700427 extRangeVar := "extRange_" + message.GoIdent.GoName
428 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
429 for i := 0; i < extranges.Len(); i++ {
430 r := extranges.Get(i)
431 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
432 }
433 g.P("}")
434 g.P()
435 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
436 g.P("return ", extRangeVar)
437 g.P("}")
438 g.P()
439 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700440
Damien Neilea7baf42018-09-28 14:23:44 -0700441 genWellKnownType(g, "*", message.GoIdent, message.Desc)
442
Damien Neila1c6abc2018-09-12 13:36:34 -0700443 // Table-driven proto support.
444 //
445 // TODO: It does not scale to keep adding another method for every
446 // operation on protos that we want to switch over to using the
447 // table-driven approach. Instead, we should only add a single method
448 // that allows getting access to the *InternalMessageInfo struct and then
449 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
450 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
451 // XXX_Unmarshal
452 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
453 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
454 g.P("}")
455 // XXX_Marshal
456 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
457 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
458 g.P("}")
459 // XXX_Merge
460 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
461 g.P(messageInfoVar, ".Merge(m, src)")
462 g.P("}")
463 // XXX_Size
464 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
465 g.P("return ", messageInfoVar, ".Size(m)")
466 g.P("}")
467 // XXX_DiscardUnknown
468 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
469 g.P(messageInfoVar, ".DiscardUnknown(m)")
470 g.P("}")
471 g.P()
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800472 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
Damien Neila1c6abc2018-09-12 13:36:34 -0700473 g.P()
474
Damien Neilebc699d2018-09-13 08:50:13 -0700475 // Constants and vars holding the default values of fields.
476 for _, field := range message.Fields {
Damien Neilccf3fa62018-09-28 14:41:45 -0700477 if !fieldHasDefault(field) {
Damien Neilebc699d2018-09-13 08:50:13 -0700478 continue
479 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700480 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700481 def := field.Desc.Default()
482 switch field.Desc.Kind() {
483 case protoreflect.StringKind:
484 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
485 case protoreflect.BytesKind:
486 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
487 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700488 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700489 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700490 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700491 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
492 case protoreflect.FloatKind, protoreflect.DoubleKind:
493 // Floating point numbers need extra handling for -Inf/Inf/NaN.
494 f := field.Desc.Default().Float()
495 goType := "float64"
496 if field.Desc.Kind() == protoreflect.FloatKind {
497 goType = "float32"
498 }
499 // funcCall returns a call to a function in the math package,
500 // possibly converting the result to float32.
501 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800502 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700503 if goType != "float64" {
504 s = goType + "(" + s + ")"
505 }
506 return s
507 }
508 switch {
509 case math.IsInf(f, -1):
510 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
511 case math.IsInf(f, 1):
512 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
513 case math.IsNaN(f):
514 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
515 default:
Damien Neil982684b2018-09-28 14:12:41 -0700516 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700517 }
518 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700519 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700520 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
521 }
522 }
523 g.P()
524
Damien Neil77f82fe2018-09-13 10:59:17 -0700525 // Getters.
526 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700527 if field.OneofType != nil {
528 if field == field.OneofType.Fields[0] {
529 genOneofTypes(gen, g, f, message, field.OneofType)
530 }
531 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700532 goType, pointer := fieldGoType(g, field)
533 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil204f1c02018-10-23 15:03:38 -0700534 if field.Desc.Options().(*descpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700535 g.P(deprecationComment(true))
536 }
Damien Neil162c1272018-10-04 12:42:37 -0700537 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700538 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
539 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700540 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700541 g.P("return x.", field.GoName)
542 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700543 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700544 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
545 g.P("if m != nil {")
546 } else {
547 g.P("if m != nil && m.", field.GoName, " != nil {")
548 }
549 star := ""
550 if pointer {
551 star = "*"
552 }
553 g.P("return ", star, " m.", field.GoName)
554 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700555 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700556 g.P("return ", defaultValue)
557 g.P("}")
558 g.P()
559 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700560
Damien Neil1fa78d82018-09-13 13:12:36 -0700561 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800562 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700563 }
Damien Neil993c04d2018-09-14 15:41:11 -0700564 for _, extension := range message.Extensions {
565 genExtension(gen, g, f, extension)
566 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700567}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700568
Damien Neil77f82fe2018-09-13 10:59:17 -0700569// fieldGoType returns the Go type used for a field.
570//
571// If it returns pointer=true, the struct field is a pointer to the type.
572func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700573 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700574 switch field.Desc.Kind() {
575 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700576 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700577 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700578 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700579 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700580 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700581 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700582 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700583 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700584 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700585 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700586 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700587 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700588 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700589 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700590 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700591 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700592 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700593 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700594 goType = "[]byte"
595 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700596 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700597 if field.Desc.IsMap() {
598 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
599 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
600 return fmt.Sprintf("map[%v]%v", keyType, valType), false
601 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700602 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
603 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700604 }
605 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700606 goType = "[]" + goType
607 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700608 }
Damien Neil44000a12018-10-24 12:31:16 -0700609 // Extension fields always have pointer type, even when defined in a proto3 file.
610 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700611 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700612 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700613 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700614}
615
616func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700617 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700618 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700619 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700620 }
Joe Tsai05828db2018-11-01 13:52:16 -0700621 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700622}
623
Damien Neil77f82fe2018-09-13 10:59:17 -0700624func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
625 if field.Desc.Cardinality() == protoreflect.Repeated {
626 return "nil"
627 }
Damien Neilccf3fa62018-09-28 14:41:45 -0700628 if fieldHasDefault(field) {
Damien Neil1fa78d82018-09-13 13:12:36 -0700629 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 if field.Desc.Kind() == protoreflect.BytesKind {
631 return "append([]byte(nil), " + defVarName + "...)"
632 }
633 return defVarName
634 }
635 switch field.Desc.Kind() {
636 case protoreflect.BoolKind:
637 return "false"
638 case protoreflect.StringKind:
639 return `""`
640 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
641 return "nil"
642 case protoreflect.EnumKind:
643 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
644 default:
645 return "0"
646 }
647}
648
Damien Neilccf3fa62018-09-28 14:41:45 -0700649// fieldHasDefault returns true if we consider a field to have a default value.
650//
651// For consistency with the previous generator, it returns false for fields with
652// [default=""], preventing the generation of a default const or var for these
653// fields.
654//
655// TODO: Drop this special case.
656func fieldHasDefault(field *protogen.Field) bool {
657 if !field.Desc.HasDefault() {
658 return false
659 }
660 switch field.Desc.Kind() {
661 case protoreflect.StringKind:
662 return field.Desc.Default().String() != ""
663 case protoreflect.BytesKind:
664 return len(field.Desc.Default().Bytes()) > 0
665 }
666 return true
667}
668
Damien Neil658051b2018-09-10 12:26:21 -0700669func fieldJSONTag(field *protogen.Field) string {
670 return string(field.Desc.Name()) + ",omitempty"
671}
672
Damien Neild39efc82018-09-24 12:38:10 -0700673func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700674 // Special case for proto2 message sets: If this extension is extending
675 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
676 // then drop that last component.
677 //
678 // TODO: This should be implemented in the text formatter rather than the generator.
679 // In addition, the situation for when to apply this special case is implemented
680 // differently in other languages:
681 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
682 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700683 if n, ok := isExtensionMessageSetElement(extension); ok {
684 name = n
Damien Neil154da982018-09-19 13:21:58 -0700685 }
686
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800687 g.P("var ", extensionVar(f.File, extension), " = &", protoPackage.Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700688 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
689 goType, pointer := fieldGoType(g, extension)
690 if pointer {
691 goType = "*" + goType
692 }
693 g.P("ExtensionType: (", goType, ")(nil),")
694 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700695 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700696 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
697 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
698 g.P("}")
699 g.P()
700}
701
Damien Neil62386962018-10-30 10:35:48 -0700702// isExtensionMessageSetELement returns the adjusted name of an extension
703// which extends proto2.bridge.MessageSet.
704func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
705 opts := extension.ExtendedType.Desc.Options().(*descpb.MessageOptions)
706 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
707 return "", false
708 }
709 if extension.ParentMessage == nil {
710 // This case shouldn't be given special handling at all--we're
711 // only supposed to drop the ".message_set_extension" for
712 // extensions defined within a message (i.e., the extension
713 // takes the message's name).
714 //
715 // This matches the behavior of the v1 generator, however.
716 //
717 // TODO: See if we can drop this case.
718 name = extension.Desc.FullName()
719 name = name[:len(name)-len("message_set_extension")]
720 return name, true
721 }
722 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700723}
724
Damien Neil993c04d2018-09-14 15:41:11 -0700725// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700726func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700727 name := "E_"
728 if extension.ParentMessage != nil {
729 name += extension.ParentMessage.GoIdent.GoName + "_"
730 }
731 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800732 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700733}
734
Damien Neilce36f8d2018-09-13 15:19:08 -0700735// genInitFunction generates an init function that registers the types in the
736// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700737func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil993c04d2018-09-14 15:41:11 -0700738 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700739 return
740 }
741
742 g.P("func init() {")
Damien Neil154da982018-09-19 13:21:58 -0700743 for _, enum := range f.allEnums {
744 name := enum.GoIdent.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800745 g.P(protoPackage.Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700746 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700747 for _, message := range f.allMessages {
748 if message.Desc.IsMapEntry() {
749 continue
750 }
751
Damien Neil154da982018-09-19 13:21:58 -0700752 for _, extension := range message.Extensions {
753 genRegisterExtension(gen, g, f, extension)
754 }
755
Damien Neilce36f8d2018-09-13 15:19:08 -0700756 name := message.GoIdent.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800757 g.P(protoPackage.Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700758
759 // Types of map fields, sorted by the name of the field message type.
760 var mapFields []*protogen.Field
761 for _, field := range message.Fields {
762 if field.Desc.IsMap() {
763 mapFields = append(mapFields, field)
764 }
765 }
766 sort.Slice(mapFields, func(i, j int) bool {
767 ni := mapFields[i].MessageType.Desc.FullName()
768 nj := mapFields[j].MessageType.Desc.FullName()
769 return ni < nj
770 })
771 for _, field := range mapFields {
772 typeName := string(field.MessageType.Desc.FullName())
773 goType, _ := fieldGoType(g, field)
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800774 g.P(protoPackage.Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700775 }
776 }
Damien Neil154da982018-09-19 13:21:58 -0700777 for _, extension := range f.Extensions {
778 genRegisterExtension(gen, g, f, extension)
Damien Neil993c04d2018-09-14 15:41:11 -0700779 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700780 g.P("}")
781 g.P()
782}
783
Damien Neild39efc82018-09-24 12:38:10 -0700784func genRegisterExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800785 g.P(protoPackage.Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil154da982018-09-19 13:21:58 -0700786}
787
Damien Neil55fe1c02018-09-17 15:11:24 -0700788// deprecationComment returns a standard deprecation comment if deprecated is true.
789func deprecationComment(deprecated bool) string {
790 if !deprecated {
791 return ""
792 }
793 return "// Deprecated: Do not use."
794}
795
Damien Neilea7baf42018-09-28 14:23:44 -0700796func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700797 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700798 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700799 g.P()
800 }
801}
802
803// Names of messages and enums for which we will generate XXX_WellKnownType methods.
804var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700805 "google.protobuf.Any": true,
806 "google.protobuf.Duration": true,
807 "google.protobuf.Empty": true,
808 "google.protobuf.Struct": true,
809 "google.protobuf.Timestamp": true,
810
811 "google.protobuf.BoolValue": true,
812 "google.protobuf.BytesValue": true,
813 "google.protobuf.DoubleValue": true,
814 "google.protobuf.FloatValue": true,
815 "google.protobuf.Int32Value": true,
816 "google.protobuf.Int64Value": true,
817 "google.protobuf.ListValue": true,
818 "google.protobuf.NullValue": true,
819 "google.protobuf.StringValue": true,
820 "google.protobuf.UInt32Value": true,
821 "google.protobuf.UInt64Value": true,
822 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700823}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800824
825// genOneofField generates the struct field for a oneof.
826func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
827 if g.PrintLeadingComments(oneof.Location) {
828 g.P("//")
829 }
830 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
831 for _, field := range oneof.Fields {
832 g.PrintLeadingComments(field.Location)
833 g.P("//\t*", fieldOneofType(field))
834 }
835 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
836 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
837}
838
839// genOneofTypes generates the interface type used for a oneof field,
840// and the wrapper types that satisfy that interface.
841//
842// It also generates the getter method for the parent oneof field
843// (but not the member fields).
844func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
845 ifName := oneofInterfaceName(oneof)
846 g.P("type ", ifName, " interface {")
847 g.P(ifName, "()")
848 g.P("}")
849 g.P()
850 for _, field := range oneof.Fields {
851 name := fieldOneofType(field)
852 g.Annotate(name.GoName, field.Location)
853 g.Annotate(name.GoName+"."+field.GoName, field.Location)
854 g.P("type ", name, " struct {")
855 goType, _ := fieldGoType(g, field)
856 tags := []string{
857 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
858 }
859 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
860 g.P("}")
861 g.P()
862 }
863 for _, field := range oneof.Fields {
864 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
865 g.P()
866 }
867 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
868 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
869 g.P("if m != nil {")
870 g.P("return m.", oneofFieldName(oneof))
871 g.P("}")
872 g.P("return nil")
873 g.P("}")
874 g.P()
875}
876
877// oneofFieldName returns the name of the struct field holding the oneof value.
878//
879// This function is trivial, but pulling out the name like this makes it easier
880// to experiment with alternative oneof implementations.
881func oneofFieldName(oneof *protogen.Oneof) string {
882 return oneof.GoName
883}
884
885// oneofInterfaceName returns the name of the interface type implemented by
886// the oneof field value types.
887func oneofInterfaceName(oneof *protogen.Oneof) string {
888 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
889}
890
891// genOneofWrappers generates the XXX_OneofWrappers method for a message.
892func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
893 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
894 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
895 g.P("return []interface{}{")
896 for _, oneof := range message.Oneofs {
897 for _, field := range oneof.Fields {
898 g.P("(*", fieldOneofType(field), ")(nil),")
899 }
900 }
901 g.P("}")
902 g.P("}")
903 g.P()
904}
905
906// fieldOneofType returns the wrapper type used to represent a field in a oneof.
907func fieldOneofType(field *protogen.Field) protogen.GoIdent {
908 ident := protogen.GoIdent{
909 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
910 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
911 }
912 // Check for collisions with nested messages or enums.
913 //
914 // This conflict resolution is incomplete: Among other things, it
915 // does not consider collisions with other oneof field types.
916 //
917 // TODO: Consider dropping this entirely. Detecting conflicts and
918 // producing an error is almost certainly better than permuting
919 // field and type names in mostly unpredictable ways.
920Loop:
921 for {
922 for _, message := range field.ParentMessage.Messages {
923 if message.GoIdent == ident {
924 ident.GoName += "_"
925 continue Loop
926 }
927 }
928 for _, enum := range field.ParentMessage.Enums {
929 if enum.GoIdent == ident {
930 ident.GoName += "_"
931 continue Loop
932 }
933 }
934 return ident
935 }
936}