blob: a0a65cbd638fb3ace0803934866081a57e26a83e [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 Tsai01ab2962018-09-21 17:44:00 -070021 "github.com/golang/protobuf/v2/protogen"
22 "github.com/golang/protobuf/v2/reflect/protoreflect"
Damien Neil220c2022018-08-15 11:24:18 -070023)
24
Damien Neild4127922018-09-12 11:13:49 -070025// generatedCodeVersion indicates a version of the generated code.
26// It is incremented whenever an incompatibility between the generated code and
27// proto package is introduced; the generated code references
28// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
29const generatedCodeVersion = 2
30
Damien Neil46abb572018-09-07 12:45:37 -070031const protoPackage = "github.com/golang/protobuf/proto"
32
Damien Neild39efc82018-09-24 12:38:10 -070033type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070034 *protogen.File
Damien Neil46abb572018-09-07 12:45:37 -070035 locationMap map[string][]*descpb.SourceCodeInfo_Location
36 descriptorVar string // var containing the gzipped FileDescriptorProto
Damien Neilce36f8d2018-09-13 15:19:08 -070037 allEnums []*protogen.Enum
38 allMessages []*protogen.Message
Damien Neil993c04d2018-09-14 15:41:11 -070039 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070040}
41
Damien Neil9c420a62018-09-27 15:26:33 -070042// GenerateFile generates the contents of a .pb.go file.
43func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070044 f := &fileInfo{
Damien Neilcab8dfe2018-09-06 14:51:28 -070045 File: file,
46 locationMap: make(map[string][]*descpb.SourceCodeInfo_Location),
47 }
48 for _, loc := range file.Proto.GetSourceCodeInfo().GetLocation() {
49 key := pathKey(loc.Path)
50 f.locationMap[key] = append(f.locationMap[key], loc)
51 }
52
Damien Neil993c04d2018-09-14 15:41:11 -070053 // The different order for enums and extensions is to match the output
54 // of the previous implementation.
55 //
56 // TODO: Eventually make this consistent.
Damien Neilce36f8d2018-09-13 15:19:08 -070057 f.allEnums = append(f.allEnums, f.File.Enums...)
Damien Neil73ac8852018-09-17 15:11:24 -070058 walkMessages(f.Messages, func(message *protogen.Message) {
59 f.allMessages = append(f.allMessages, message)
60 f.allEnums = append(f.allEnums, message.Enums...)
61 f.allExtensions = append(f.allExtensions, message.Extensions...)
62 })
Damien Neil993c04d2018-09-14 15:41:11 -070063 f.allExtensions = append(f.allExtensions, f.File.Extensions...)
Damien Neilce36f8d2018-09-13 15:19:08 -070064
Damien Neil46abb572018-09-07 12:45:37 -070065 // Determine the name of the var holding the file descriptor:
66 //
67 // fileDescriptor_<hash of filename>
68 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
69 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
70
Damien Neil220c2022018-08-15 11:24:18 -070071 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070072 if f.Proto.GetOptions().GetDeprecated() {
73 g.P("// ", f.Desc.Path(), " is a deprecated file.")
74 } else {
75 g.P("// source: ", f.Desc.Path())
76 }
Damien Neil220c2022018-08-15 11:24:18 -070077 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070078 const filePackageField = 2 // FileDescriptorProto.package
79 genComment(g, f, []int32{filePackageField})
80 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070081 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070082 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -070083
84 // These references are not necessary, since we automatically add
85 // all necessary imports before formatting the generated file.
86 //
87 // This section exists to generate output more consistent with
88 // the previous version of protoc-gen-go, to make it easier to
89 // detect unintended variations.
90 //
91 // TODO: Eventually remove this.
92 g.P("// Reference imports to suppress errors if they are not otherwise used.")
93 g.P("var _ = ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "Marshal"})
94 g.P("var _ = ", protogen.GoIdent{GoImportPath: "fmt", GoName: "Errorf"})
95 g.P("var _ = ", protogen.GoIdent{GoImportPath: "math", GoName: "Inf"})
96 g.P()
97
Damien Neild4127922018-09-12 11:13:49 -070098 g.P("// This is a compile-time assertion to ensure that this generated file")
99 g.P("// is compatible with the proto package it is being compiled against.")
100 g.P("// A compilation error at this line likely means your copy of the")
101 g.P("// proto package needs to be updated.")
102 g.P("const _ = ", protogen.GoIdent{
103 GoImportPath: protoPackage,
104 GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion),
105 }, "// please upgrade the proto package")
106 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 }
142 // Generate imports for all dependencies, even if they are not
143 // referenced, because other code and tools depend on having the
144 // full transitive closure of protocol buffer types in the binary.
145 g.Import(impFile.GoImportPath)
146 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700147 return
148 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700149 // TODO: An alternate approach to generating public imports might be
150 // to generate the imported file contents, parse it, and extract all
151 // exported identifiers from the AST to build a list of forwarding
152 // declarations.
153 //
154 // TODO: Consider whether this should generate recursive aliases. e.g.,
155 // if a.proto publicly imports b.proto publicly imports c.proto, should
156 // a.pb.go contain aliases for symbols defined in c.proto?
Damien Neil73ac8852018-09-17 15:11:24 -0700157 var enums []*protogen.Enum
158 enums = append(enums, impFile.Enums...)
159 walkMessages(impFile.Messages, func(message *protogen.Message) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700160 if message.Desc.IsMapEntry() {
161 return
162 }
Damien Neil73ac8852018-09-17 15:11:24 -0700163 enums = append(enums, message.Enums...)
Damien Neil2193e8d2018-10-09 12:49:13 -0700164 for _, field := range message.Fields {
165 if !fieldHasDefault(field) {
166 continue
167 }
168 defVar := protogen.GoIdent{
169 GoImportPath: message.GoIdent.GoImportPath,
170 GoName: "Default_" + message.GoIdent.GoName + "_" + field.GoName,
171 }
172 decl := "const"
173 if field.Desc.Kind() == protoreflect.BytesKind {
174 decl = "var"
175 }
176 g.P(decl, " ", defVar.GoName, " = ", defVar)
177 }
Damien Neil73ac8852018-09-17 15:11:24 -0700178 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
179 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
180 for _, oneof := range message.Oneofs {
181 for _, field := range oneof.Fields {
182 typ := fieldOneofType(field)
183 g.P("type ", typ.GoName, " = ", typ)
184 }
185 }
186 g.P()
187 })
188 for _, enum := range enums {
189 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
190 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
191 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
192 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
193 g.P()
194 for _, value := range enum.Values {
195 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
196 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700197 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700198 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700199}
200
Damien Neild39efc82018-09-24 12:38:10 -0700201func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700202 // Trim the source_code_info from the descriptor.
203 // Marshal and gzip it.
204 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
205 descProto.SourceCodeInfo = nil
206 b, err := proto.Marshal(descProto)
207 if err != nil {
208 gen.Error(err)
209 return
210 }
211 var buf bytes.Buffer
212 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
213 w.Write(b)
214 w.Close()
215 b = buf.Bytes()
216
Damien Neil46abb572018-09-07 12:45:37 -0700217 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700218 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700219 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700220 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
221 for len(b) > 0 {
222 n := 16
223 if n > len(b) {
224 n = len(b)
225 }
226
227 s := ""
228 for _, c := range b[:n] {
229 s += fmt.Sprintf("0x%02x,", c)
230 }
231 g.P(s)
232
233 b = b[n:]
234 }
235 g.P("}")
236 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700237}
Damien Neilc7d07d92018-08-22 13:46:02 -0700238
Damien Neild39efc82018-09-24 12:38:10 -0700239func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neil46abb572018-09-07 12:45:37 -0700240 genComment(g, f, enum.Path)
Damien Neil55fe1c02018-09-17 15:11:24 -0700241 g.P("type ", enum.GoIdent, " int32",
242 deprecationComment(enumOptions(gen, enum).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700243 g.P("const (")
244 for _, value := range enum.Values {
245 genComment(g, f, value.Path)
Damien Neil55fe1c02018-09-17 15:11:24 -0700246 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
247 deprecationComment(enumValueOptions(gen, value).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700248 }
249 g.P(")")
250 g.P()
251 nameMap := enum.GoIdent.GoName + "_name"
252 g.P("var ", nameMap, " = map[int32]string{")
253 generated := make(map[protoreflect.EnumNumber]bool)
254 for _, value := range enum.Values {
255 duplicate := ""
256 if _, present := generated[value.Desc.Number()]; present {
257 duplicate = "// Duplicate value: "
258 }
259 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
260 generated[value.Desc.Number()] = true
261 }
262 g.P("}")
263 g.P()
264 valueMap := enum.GoIdent.GoName + "_value"
265 g.P("var ", valueMap, " = map[string]int32{")
266 for _, value := range enum.Values {
267 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
268 }
269 g.P("}")
270 g.P()
271 if enum.Desc.Syntax() != protoreflect.Proto3 {
272 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
273 g.P("p := new(", enum.GoIdent, ")")
274 g.P("*p = x")
275 g.P("return p")
276 g.P("}")
277 g.P()
278 }
279 g.P("func (x ", enum.GoIdent, ") String() string {")
280 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
281 g.P("}")
282 g.P()
283
284 if enum.Desc.Syntax() != protoreflect.Proto3 {
285 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
286 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
287 g.P("if err != nil {")
288 g.P("return err")
289 g.P("}")
290 g.P("*x = ", enum.GoIdent, "(value)")
291 g.P("return nil")
292 g.P("}")
293 g.P()
294 }
295
296 var indexes []string
297 for i := 1; i < len(enum.Path); i += 2 {
298 indexes = append(indexes, strconv.Itoa(int(enum.Path[i])))
299 }
300 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
301 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
302 g.P("}")
303 g.P()
304
Damien Neilea7baf42018-09-28 14:23:44 -0700305 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700306}
307
Damien Neil658051b2018-09-10 12:26:21 -0700308// enumRegistryName returns the name used to register an enum with the proto
309// package registry.
310//
311// Confusingly, this is <proto_package>.<go_ident>. This probably should have
312// been the full name of the proto enum type instead, but changing it at this
313// point would require thought.
314func enumRegistryName(enum *protogen.Enum) string {
315 // Find the FileDescriptor for this enum.
316 var desc protoreflect.Descriptor = enum.Desc
317 for {
318 p, ok := desc.Parent()
319 if !ok {
320 break
321 }
322 desc = p
323 }
324 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700325 if fdesc.Package() == "" {
326 return enum.GoIdent.GoName
327 }
Damien Neil658051b2018-09-10 12:26:21 -0700328 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
329}
330
Damien Neild39efc82018-09-24 12:38:10 -0700331func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700332 if message.Desc.IsMapEntry() {
333 return
334 }
335
Damien Neil55fe1c02018-09-17 15:11:24 -0700336 hasComment := genComment(g, f, message.Path)
337 if messageOptions(gen, message).GetDeprecated() {
338 if hasComment {
339 g.P("//")
340 }
341 g.P(deprecationComment(true))
342 }
Damien Neilcab8dfe2018-09-06 14:51:28 -0700343 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700344 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700345 if field.OneofType != nil {
346 // It would be a bit simpler to iterate over the oneofs below,
347 // but generating the field here keeps the contents of the Go
348 // struct in the same order as the contents of the source
349 // .proto file.
350 if field == field.OneofType.Fields[0] {
351 genOneofField(gen, g, f, message, field.OneofType)
352 }
Damien Neil658051b2018-09-10 12:26:21 -0700353 continue
354 }
355 genComment(g, f, field.Path)
Damien Neil77f82fe2018-09-13 10:59:17 -0700356 goType, pointer := fieldGoType(g, field)
357 if pointer {
358 goType = "*" + goType
359 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700360 tags := []string{
361 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
362 fmt.Sprintf("json:%q", fieldJSONTag(field)),
363 }
364 if field.Desc.IsMap() {
365 key := field.MessageType.Fields[0]
366 val := field.MessageType.Fields[1]
367 tags = append(tags,
368 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
369 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
370 )
371 }
Damien Neil55fe1c02018-09-17 15:11:24 -0700372 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
373 deprecationComment(fieldOptions(gen, field).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700374 }
375 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700376
377 if message.Desc.ExtensionRanges().Len() > 0 {
378 var tags []string
379 if messageOptions(gen, message).GetMessageSetWireFormat() {
380 tags = append(tags, `protobuf_messageset:"1"`)
381 }
382 tags = append(tags, `json:"-"`)
383 g.P(protogen.GoIdent{
384 GoImportPath: protoPackage,
385 GoName: "XXX_InternalExtensions",
386 }, " `", strings.Join(tags, " "), "`")
387 }
Damien Neil658051b2018-09-10 12:26:21 -0700388 // TODO XXX_InternalExtensions
389 g.P("XXX_unrecognized []byte `json:\"-\"`")
390 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700391 g.P("}")
392 g.P()
393
Damien Neila1c6abc2018-09-12 13:36:34 -0700394 // Reset
395 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
396 // String
397 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
398 GoImportPath: protoPackage,
399 GoName: "CompactTextString",
400 }, "(m) }")
401 // ProtoMessage
402 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
403 // Descriptor
404 var indexes []string
405 for i := 1; i < len(message.Path); i += 2 {
406 indexes = append(indexes, strconv.Itoa(int(message.Path[i])))
407 }
408 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
409 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
410 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700411 g.P()
412
413 // ExtensionRangeArray
414 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
415 if messageOptions(gen, message).GetMessageSetWireFormat() {
416 g.P("func (m *", message.GoIdent, ") MarshalJSON() ([]byte, error) {")
417 g.P("return ", protogen.GoIdent{
418 GoImportPath: protoPackage,
419 GoName: "MarshalMessageSetJSON",
420 }, "(&m.XXX_InternalExtensions)")
421 g.P("}")
422 g.P("func (m *", message.GoIdent, ") UnmarshalJSON(buf []byte) error {")
423 g.P("return ", protogen.GoIdent{
424 GoImportPath: protoPackage,
425 GoName: "UnmarshalMessageSetJSON",
426 }, "(buf, &m.XXX_InternalExtensions)")
427 g.P("}")
428 g.P()
429 }
430
431 protoExtRange := protogen.GoIdent{
432 GoImportPath: protoPackage,
433 GoName: "ExtensionRange",
434 }
435 extRangeVar := "extRange_" + message.GoIdent.GoName
436 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
437 for i := 0; i < extranges.Len(); i++ {
438 r := extranges.Get(i)
439 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
440 }
441 g.P("}")
442 g.P()
443 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
444 g.P("return ", extRangeVar)
445 g.P("}")
446 g.P()
447 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700448
Damien Neilea7baf42018-09-28 14:23:44 -0700449 genWellKnownType(g, "*", message.GoIdent, message.Desc)
450
Damien Neila1c6abc2018-09-12 13:36:34 -0700451 // Table-driven proto support.
452 //
453 // TODO: It does not scale to keep adding another method for every
454 // operation on protos that we want to switch over to using the
455 // table-driven approach. Instead, we should only add a single method
456 // that allows getting access to the *InternalMessageInfo struct and then
457 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
458 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
459 // XXX_Unmarshal
460 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
461 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
462 g.P("}")
463 // XXX_Marshal
464 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
465 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
466 g.P("}")
467 // XXX_Merge
468 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
469 g.P(messageInfoVar, ".Merge(m, src)")
470 g.P("}")
471 // XXX_Size
472 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
473 g.P("return ", messageInfoVar, ".Size(m)")
474 g.P("}")
475 // XXX_DiscardUnknown
476 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
477 g.P(messageInfoVar, ".DiscardUnknown(m)")
478 g.P("}")
479 g.P()
480 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
481 GoImportPath: protoPackage,
482 GoName: "InternalMessageInfo",
483 })
484 g.P()
485
Damien Neilebc699d2018-09-13 08:50:13 -0700486 // Constants and vars holding the default values of fields.
487 for _, field := range message.Fields {
Damien Neilccf3fa62018-09-28 14:41:45 -0700488 if !fieldHasDefault(field) {
Damien Neilebc699d2018-09-13 08:50:13 -0700489 continue
490 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700491 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700492 def := field.Desc.Default()
493 switch field.Desc.Kind() {
494 case protoreflect.StringKind:
495 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
496 case protoreflect.BytesKind:
497 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
498 case protoreflect.EnumKind:
499 enum := field.EnumType
500 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
501 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
502 case protoreflect.FloatKind, protoreflect.DoubleKind:
503 // Floating point numbers need extra handling for -Inf/Inf/NaN.
504 f := field.Desc.Default().Float()
505 goType := "float64"
506 if field.Desc.Kind() == protoreflect.FloatKind {
507 goType = "float32"
508 }
509 // funcCall returns a call to a function in the math package,
510 // possibly converting the result to float32.
511 funcCall := func(fn, param string) string {
512 s := g.QualifiedGoIdent(protogen.GoIdent{
513 GoImportPath: "math",
514 GoName: fn,
515 }) + param
516 if goType != "float64" {
517 s = goType + "(" + s + ")"
518 }
519 return s
520 }
521 switch {
522 case math.IsInf(f, -1):
523 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
524 case math.IsInf(f, 1):
525 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
526 case math.IsNaN(f):
527 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
528 default:
Damien Neil982684b2018-09-28 14:12:41 -0700529 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700530 }
531 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700532 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700533 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
534 }
535 }
536 g.P()
537
Damien Neil77f82fe2018-09-13 10:59:17 -0700538 // Getters.
539 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700540 if field.OneofType != nil {
541 if field == field.OneofType.Fields[0] {
542 genOneofTypes(gen, g, f, message, field.OneofType)
543 }
544 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700545 goType, pointer := fieldGoType(g, field)
546 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil55fe1c02018-09-17 15:11:24 -0700547 if fieldOptions(gen, field).GetDeprecated() {
548 g.P(deprecationComment(true))
549 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700550 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
551 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700552 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700553 g.P("return x.", field.GoName)
554 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700555 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700556 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
557 g.P("if m != nil {")
558 } else {
559 g.P("if m != nil && m.", field.GoName, " != nil {")
560 }
561 star := ""
562 if pointer {
563 star = "*"
564 }
565 g.P("return ", star, " m.", field.GoName)
566 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700567 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700568 g.P("return ", defaultValue)
569 g.P("}")
570 g.P()
571 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700572
Damien Neil1fa78d82018-09-13 13:12:36 -0700573 if len(message.Oneofs) > 0 {
574 genOneofFuncs(gen, g, f, message)
575 }
Damien Neil993c04d2018-09-14 15:41:11 -0700576 for _, extension := range message.Extensions {
577 genExtension(gen, g, f, extension)
578 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700579}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700580
Damien Neil77f82fe2018-09-13 10:59:17 -0700581// fieldGoType returns the Go type used for a field.
582//
583// If it returns pointer=true, the struct field is a pointer to the type.
584func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700585 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700586 switch field.Desc.Kind() {
587 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700588 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700589 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700590 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700591 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700592 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700593 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700594 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700595 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700596 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700597 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700598 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700599 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700600 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700601 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700602 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700603 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700604 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700605 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700606 goType = "[]byte"
607 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700608 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700609 if field.Desc.IsMap() {
610 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
611 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
612 return fmt.Sprintf("map[%v]%v", keyType, valType), false
613 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
615 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700616 }
617 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = "[]" + goType
619 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700620 }
621 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700623 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700625}
626
627func fieldProtobufTag(field *protogen.Field) string {
628 var tag []string
629 // wire type
630 tag = append(tag, wireTypes[field.Desc.Kind()])
631 // field number
632 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
633 // cardinality
634 switch field.Desc.Cardinality() {
635 case protoreflect.Optional:
636 tag = append(tag, "opt")
637 case protoreflect.Required:
638 tag = append(tag, "req")
639 case protoreflect.Repeated:
640 tag = append(tag, "rep")
641 }
Damien Neild4803f52018-09-19 11:43:35 -0700642 if field.Desc.IsPacked() {
643 tag = append(tag, "packed")
644 }
Damien Neil658051b2018-09-10 12:26:21 -0700645 // TODO: packed
646 // name
647 name := string(field.Desc.Name())
648 if field.Desc.Kind() == protoreflect.GroupKind {
649 // The name of the FieldDescriptor for a group field is
650 // lowercased. To find the original capitalization, we
651 // look in the field's MessageType.
652 name = string(field.MessageType.Desc.Name())
653 }
654 tag = append(tag, "name="+name)
655 // JSON name
656 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
657 tag = append(tag, "json="+jsonName)
658 }
659 // proto3
660 if field.Desc.Syntax() == protoreflect.Proto3 {
661 tag = append(tag, "proto3")
662 }
663 // enum
664 if field.Desc.Kind() == protoreflect.EnumKind {
665 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
666 }
667 // oneof
668 if field.Desc.OneofType() != nil {
669 tag = append(tag, "oneof")
670 }
Damien Neilebc699d2018-09-13 08:50:13 -0700671 // default value
672 // This must appear last in the tag, since commas in strings aren't escaped.
673 if field.Desc.HasDefault() {
674 var def string
675 switch field.Desc.Kind() {
676 case protoreflect.BoolKind:
677 if field.Desc.Default().Bool() {
678 def = "1"
679 } else {
680 def = "0"
681 }
682 case protoreflect.BytesKind:
683 def = string(field.Desc.Default().Bytes())
684 case protoreflect.FloatKind, protoreflect.DoubleKind:
685 f := field.Desc.Default().Float()
686 switch {
687 case math.IsInf(f, -1):
688 def = "-inf"
689 case math.IsInf(f, 1):
690 def = "inf"
691 case math.IsNaN(f):
692 def = "nan"
693 default:
Damien Neil982684b2018-09-28 14:12:41 -0700694 def = fmt.Sprint(field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700695 }
696 default:
697 def = fmt.Sprint(field.Desc.Default().Interface())
698 }
699 tag = append(tag, "def="+def)
700 }
Damien Neil658051b2018-09-10 12:26:21 -0700701 return strings.Join(tag, ",")
702}
703
Damien Neil77f82fe2018-09-13 10:59:17 -0700704func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
705 if field.Desc.Cardinality() == protoreflect.Repeated {
706 return "nil"
707 }
Damien Neilccf3fa62018-09-28 14:41:45 -0700708 if fieldHasDefault(field) {
Damien Neil1fa78d82018-09-13 13:12:36 -0700709 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700710 if field.Desc.Kind() == protoreflect.BytesKind {
711 return "append([]byte(nil), " + defVarName + "...)"
712 }
713 return defVarName
714 }
715 switch field.Desc.Kind() {
716 case protoreflect.BoolKind:
717 return "false"
718 case protoreflect.StringKind:
719 return `""`
720 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
721 return "nil"
722 case protoreflect.EnumKind:
723 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
724 default:
725 return "0"
726 }
727}
728
Damien Neilccf3fa62018-09-28 14:41:45 -0700729// fieldHasDefault returns true if we consider a field to have a default value.
730//
731// For consistency with the previous generator, it returns false for fields with
732// [default=""], preventing the generation of a default const or var for these
733// fields.
734//
735// TODO: Drop this special case.
736func fieldHasDefault(field *protogen.Field) bool {
737 if !field.Desc.HasDefault() {
738 return false
739 }
740 switch field.Desc.Kind() {
741 case protoreflect.StringKind:
742 return field.Desc.Default().String() != ""
743 case protoreflect.BytesKind:
744 return len(field.Desc.Default().Bytes()) > 0
745 }
746 return true
747}
748
Damien Neil658051b2018-09-10 12:26:21 -0700749var wireTypes = map[protoreflect.Kind]string{
750 protoreflect.BoolKind: "varint",
751 protoreflect.EnumKind: "varint",
752 protoreflect.Int32Kind: "varint",
753 protoreflect.Sint32Kind: "zigzag32",
754 protoreflect.Uint32Kind: "varint",
755 protoreflect.Int64Kind: "varint",
756 protoreflect.Sint64Kind: "zigzag64",
757 protoreflect.Uint64Kind: "varint",
758 protoreflect.Sfixed32Kind: "fixed32",
759 protoreflect.Fixed32Kind: "fixed32",
760 protoreflect.FloatKind: "fixed32",
761 protoreflect.Sfixed64Kind: "fixed64",
762 protoreflect.Fixed64Kind: "fixed64",
763 protoreflect.DoubleKind: "fixed64",
764 protoreflect.StringKind: "bytes",
765 protoreflect.BytesKind: "bytes",
766 protoreflect.MessageKind: "bytes",
767 protoreflect.GroupKind: "group",
768}
769
770func fieldJSONTag(field *protogen.Field) string {
771 return string(field.Desc.Name()) + ",omitempty"
772}
773
Damien Neild39efc82018-09-24 12:38:10 -0700774func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700775 // Special case for proto2 message sets: If this extension is extending
776 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
777 // then drop that last component.
778 //
779 // TODO: This should be implemented in the text formatter rather than the generator.
780 // In addition, the situation for when to apply this special case is implemented
781 // differently in other languages:
782 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
783 name := extension.Desc.FullName()
784 if isExtensionMessageSetElement(gen, extension) {
785 name = name.Parent()
786 }
787
Damien Neil993c04d2018-09-14 15:41:11 -0700788 g.P("var ", extensionVar(f, extension), " = &", protogen.GoIdent{
789 GoImportPath: protoPackage,
790 GoName: "ExtensionDesc",
791 }, "{")
792 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
793 goType, pointer := fieldGoType(g, extension)
794 if pointer {
795 goType = "*" + goType
796 }
797 g.P("ExtensionType: (", goType, ")(nil),")
798 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700799 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700800 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
801 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
802 g.P("}")
803 g.P()
804}
805
Damien Neil154da982018-09-19 13:21:58 -0700806func isExtensionMessageSetElement(gen *protogen.Plugin, extension *protogen.Extension) bool {
807 return extension.ParentMessage != nil &&
808 messageOptions(gen, extension.ExtendedType).GetMessageSetWireFormat() &&
809 extension.Desc.Name() == "message_set_extension"
810}
811
Damien Neil993c04d2018-09-14 15:41:11 -0700812// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neild39efc82018-09-24 12:38:10 -0700813func extensionVar(f *fileInfo, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700814 name := "E_"
815 if extension.ParentMessage != nil {
816 name += extension.ParentMessage.GoIdent.GoName + "_"
817 }
818 name += extension.GoName
819 return protogen.GoIdent{
820 GoImportPath: f.GoImportPath,
821 GoName: name,
822 }
823}
824
Damien Neilce36f8d2018-09-13 15:19:08 -0700825// genInitFunction generates an init function that registers the types in the
826// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700827func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil993c04d2018-09-14 15:41:11 -0700828 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700829 return
830 }
831
832 g.P("func init() {")
Damien Neil154da982018-09-19 13:21:58 -0700833 for _, enum := range f.allEnums {
834 name := enum.GoIdent.GoName
835 g.P(protogen.GoIdent{
836 GoImportPath: protoPackage,
837 GoName: "RegisterEnum",
838 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
839 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700840 for _, message := range f.allMessages {
841 if message.Desc.IsMapEntry() {
842 continue
843 }
844
Damien Neil154da982018-09-19 13:21:58 -0700845 for _, extension := range message.Extensions {
846 genRegisterExtension(gen, g, f, extension)
847 }
848
Damien Neilce36f8d2018-09-13 15:19:08 -0700849 name := message.GoIdent.GoName
850 g.P(protogen.GoIdent{
851 GoImportPath: protoPackage,
852 GoName: "RegisterType",
853 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
854
855 // Types of map fields, sorted by the name of the field message type.
856 var mapFields []*protogen.Field
857 for _, field := range message.Fields {
858 if field.Desc.IsMap() {
859 mapFields = append(mapFields, field)
860 }
861 }
862 sort.Slice(mapFields, func(i, j int) bool {
863 ni := mapFields[i].MessageType.Desc.FullName()
864 nj := mapFields[j].MessageType.Desc.FullName()
865 return ni < nj
866 })
867 for _, field := range mapFields {
868 typeName := string(field.MessageType.Desc.FullName())
869 goType, _ := fieldGoType(g, field)
870 g.P(protogen.GoIdent{
871 GoImportPath: protoPackage,
872 GoName: "RegisterMapType",
873 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
874 }
875 }
Damien Neil154da982018-09-19 13:21:58 -0700876 for _, extension := range f.Extensions {
877 genRegisterExtension(gen, g, f, extension)
Damien Neil993c04d2018-09-14 15:41:11 -0700878 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700879 g.P("}")
880 g.P()
881}
882
Damien Neild39efc82018-09-24 12:38:10 -0700883func genRegisterExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700884 g.P(protogen.GoIdent{
885 GoImportPath: protoPackage,
886 GoName: "RegisterExtension",
887 }, "(", extensionVar(f, extension), ")")
888 if isExtensionMessageSetElement(gen, extension) {
889 goType, pointer := fieldGoType(g, extension)
890 if pointer {
891 goType = "*" + goType
892 }
893 g.P(protogen.GoIdent{
894 GoImportPath: protoPackage,
895 GoName: "RegisterMessageSetType",
896 }, "((", goType, ")(nil), ", extension.Desc.Number(), ",", strconv.Quote(string(extension.Desc.FullName().Parent())), ")")
897 }
898}
899
Damien Neild39efc82018-09-24 12:38:10 -0700900func genComment(g *protogen.GeneratedFile, f *fileInfo, path []int32) (hasComment bool) {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700901 for _, loc := range f.locationMap[pathKey(path)] {
902 if loc.LeadingComments == nil {
903 continue
904 }
905 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
Damien Neil1fa78d82018-09-13 13:12:36 -0700906 hasComment = true
Damien Neilcab8dfe2018-09-06 14:51:28 -0700907 g.P("//", line)
908 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700909 break
Damien Neilcab8dfe2018-09-06 14:51:28 -0700910 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700911 return hasComment
Damien Neilcab8dfe2018-09-06 14:51:28 -0700912}
913
Damien Neil55fe1c02018-09-17 15:11:24 -0700914// deprecationComment returns a standard deprecation comment if deprecated is true.
915func deprecationComment(deprecated bool) string {
916 if !deprecated {
917 return ""
918 }
919 return "// Deprecated: Do not use."
920}
921
Damien Neilcab8dfe2018-09-06 14:51:28 -0700922// pathKey converts a location path to a string suitable for use as a map key.
923func pathKey(path []int32) string {
924 var buf []byte
925 for i, x := range path {
926 if i != 0 {
927 buf = append(buf, ',')
928 }
929 buf = strconv.AppendInt(buf, int64(x), 10)
930 }
931 return string(buf)
932}
Damien Neil46abb572018-09-07 12:45:37 -0700933
Damien Neilea7baf42018-09-28 14:23:44 -0700934func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700935 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700936 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700937 g.P()
938 }
939}
940
941// Names of messages and enums for which we will generate XXX_WellKnownType methods.
942var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700943 "google.protobuf.Any": true,
944 "google.protobuf.Duration": true,
945 "google.protobuf.Empty": true,
946 "google.protobuf.Struct": true,
947 "google.protobuf.Timestamp": true,
948
949 "google.protobuf.BoolValue": true,
950 "google.protobuf.BytesValue": true,
951 "google.protobuf.DoubleValue": true,
952 "google.protobuf.FloatValue": true,
953 "google.protobuf.Int32Value": true,
954 "google.protobuf.Int64Value": true,
955 "google.protobuf.ListValue": true,
956 "google.protobuf.NullValue": true,
957 "google.protobuf.StringValue": true,
958 "google.protobuf.UInt32Value": true,
959 "google.protobuf.UInt64Value": true,
960 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700961}