blob: 96b27fb23dae14e2a7da688b87fb38f0b957b226 [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 descriptorVar string // var containing the gzipped FileDescriptorProto
Damien Neilce36f8d2018-09-13 15:19:08 -070036 allEnums []*protogen.Enum
37 allMessages []*protogen.Message
Damien Neil993c04d2018-09-14 15:41:11 -070038 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070039}
40
Damien Neil9c420a62018-09-27 15:26:33 -070041// GenerateFile generates the contents of a .pb.go file.
42func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070043 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070044 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070045 }
46
Damien Neil993c04d2018-09-14 15:41:11 -070047 // The different order for enums and extensions is to match the output
48 // of the previous implementation.
49 //
50 // TODO: Eventually make this consistent.
Damien Neilce36f8d2018-09-13 15:19:08 -070051 f.allEnums = append(f.allEnums, f.File.Enums...)
Damien Neil73ac8852018-09-17 15:11:24 -070052 walkMessages(f.Messages, func(message *protogen.Message) {
53 f.allMessages = append(f.allMessages, message)
54 f.allEnums = append(f.allEnums, message.Enums...)
55 f.allExtensions = append(f.allExtensions, message.Extensions...)
56 })
Damien Neil993c04d2018-09-14 15:41:11 -070057 f.allExtensions = append(f.allExtensions, f.File.Extensions...)
Damien Neilce36f8d2018-09-13 15:19:08 -070058
Damien Neil46abb572018-09-07 12:45:37 -070059 // Determine the name of the var holding the file descriptor:
60 //
61 // fileDescriptor_<hash of filename>
62 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
63 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
64
Damien Neil220c2022018-08-15 11:24:18 -070065 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070066 if f.Proto.GetOptions().GetDeprecated() {
67 g.P("// ", f.Desc.Path(), " is a deprecated file.")
68 } else {
69 g.P("// source: ", f.Desc.Path())
70 }
Damien Neil220c2022018-08-15 11:24:18 -070071 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070072 const filePackageField = 2 // FileDescriptorProto.package
Damien Neilba1159f2018-10-17 12:53:18 -070073 g.PrintLeadingComments(protogen.Location{
74 SourceFile: f.Proto.GetName(),
75 Path: []int32{filePackageField},
76 })
Damien Neilcab8dfe2018-09-06 14:51:28 -070077 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070078 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070079 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -070080
81 // These references are not necessary, since we automatically add
82 // all necessary imports before formatting the generated file.
83 //
84 // This section exists to generate output more consistent with
85 // the previous version of protoc-gen-go, to make it easier to
86 // detect unintended variations.
87 //
88 // TODO: Eventually remove this.
89 g.P("// Reference imports to suppress errors if they are not otherwise used.")
90 g.P("var _ = ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "Marshal"})
91 g.P("var _ = ", protogen.GoIdent{GoImportPath: "fmt", GoName: "Errorf"})
92 g.P("var _ = ", protogen.GoIdent{GoImportPath: "math", GoName: "Inf"})
93 g.P()
94
Damien Neild4127922018-09-12 11:13:49 -070095 g.P("// This is a compile-time assertion to ensure that this generated file")
96 g.P("// is compatible with the proto package it is being compiled against.")
97 g.P("// A compilation error at this line likely means your copy of the")
98 g.P("// proto package needs to be updated.")
99 g.P("const _ = ", protogen.GoIdent{
100 GoImportPath: protoPackage,
101 GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion),
102 }, "// please upgrade the proto package")
103 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700104
Damien Neil73ac8852018-09-17 15:11:24 -0700105 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
106 genImport(gen, g, f, imps.Get(i))
107 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700108 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700109 genEnum(gen, g, f, enum)
110 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700111 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700112 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700113 }
Damien Neil993c04d2018-09-14 15:41:11 -0700114 for _, extension := range f.Extensions {
115 genExtension(gen, g, f, extension)
116 }
Damien Neil220c2022018-08-15 11:24:18 -0700117
Damien Neilce36f8d2018-09-13 15:19:08 -0700118 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700119 genFileDescriptor(gen, g, f)
120}
121
Damien Neil73ac8852018-09-17 15:11:24 -0700122// walkMessages calls f on each message and all of its descendants.
123func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
124 for _, m := range messages {
125 f(m)
126 walkMessages(m.Messages, f)
127 }
128}
129
Damien Neild39efc82018-09-24 12:38:10 -0700130func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700131 impFile, ok := gen.FileByName(imp.Path())
132 if !ok {
133 return
134 }
135 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700136 // Don't generate imports or aliases for types in the same Go package.
137 return
138 }
Damien Neil40a08052018-10-29 09:07:41 -0700139 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700140 // referenced, because other code and tools depend on having the
141 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700142 if !imp.IsWeak {
143 g.Import(impFile.GoImportPath)
144 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700145 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700146 return
147 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700148 // TODO: An alternate approach to generating public imports might be
149 // to generate the imported file contents, parse it, and extract all
150 // exported identifiers from the AST to build a list of forwarding
151 // declarations.
152 //
153 // TODO: Consider whether this should generate recursive aliases. e.g.,
154 // if a.proto publicly imports b.proto publicly imports c.proto, should
155 // a.pb.go contain aliases for symbols defined in c.proto?
Damien Neil73ac8852018-09-17 15:11:24 -0700156 var enums []*protogen.Enum
157 enums = append(enums, impFile.Enums...)
158 walkMessages(impFile.Messages, func(message *protogen.Message) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700159 if message.Desc.IsMapEntry() {
160 return
161 }
Damien Neil73ac8852018-09-17 15:11:24 -0700162 enums = append(enums, message.Enums...)
Damien Neil2193e8d2018-10-09 12:49:13 -0700163 for _, field := range message.Fields {
164 if !fieldHasDefault(field) {
165 continue
166 }
167 defVar := protogen.GoIdent{
168 GoImportPath: message.GoIdent.GoImportPath,
169 GoName: "Default_" + message.GoIdent.GoName + "_" + field.GoName,
170 }
171 decl := "const"
172 if field.Desc.Kind() == protoreflect.BytesKind {
173 decl = "var"
174 }
175 g.P(decl, " ", defVar.GoName, " = ", defVar)
176 }
Damien Neil73ac8852018-09-17 15:11:24 -0700177 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
178 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
179 for _, oneof := range message.Oneofs {
180 for _, field := range oneof.Fields {
181 typ := fieldOneofType(field)
182 g.P("type ", typ.GoName, " = ", typ)
183 }
184 }
185 g.P()
186 })
187 for _, enum := range enums {
188 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
189 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
190 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
191 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
192 g.P()
193 for _, value := range enum.Values {
194 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
195 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700196 }
Damien Neil6b541312018-10-29 09:14:14 -0700197 for _, ext := range impFile.Extensions {
198 ident := extensionVar(impFile, ext)
199 g.P("var ", ident.GoName, " = ", ident)
200 g.P()
201 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700202 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700203}
204
Damien Neild39efc82018-09-24 12:38:10 -0700205func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700206 // Trim the source_code_info from the descriptor.
207 // Marshal and gzip it.
208 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
209 descProto.SourceCodeInfo = nil
210 b, err := proto.Marshal(descProto)
211 if err != nil {
212 gen.Error(err)
213 return
214 }
215 var buf bytes.Buffer
216 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
217 w.Write(b)
218 w.Close()
219 b = buf.Bytes()
220
Damien Neil46abb572018-09-07 12:45:37 -0700221 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700222 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700223 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700224 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
225 for len(b) > 0 {
226 n := 16
227 if n > len(b) {
228 n = len(b)
229 }
230
231 s := ""
232 for _, c := range b[:n] {
233 s += fmt.Sprintf("0x%02x,", c)
234 }
235 g.P(s)
236
237 b = b[n:]
238 }
239 g.P("}")
240 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700241}
Damien Neilc7d07d92018-08-22 13:46:02 -0700242
Damien Neild39efc82018-09-24 12:38:10 -0700243func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700244 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700245 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700246 g.P("type ", enum.GoIdent, " int32",
Damien Neil204f1c02018-10-23 15:03:38 -0700247 deprecationComment(enum.Desc.Options().(*descpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700248 g.P("const (")
249 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700250 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700251 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700252 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Damien Neil204f1c02018-10-23 15:03:38 -0700253 deprecationComment(value.Desc.Options().(*descpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700254 }
255 g.P(")")
256 g.P()
257 nameMap := enum.GoIdent.GoName + "_name"
258 g.P("var ", nameMap, " = map[int32]string{")
259 generated := make(map[protoreflect.EnumNumber]bool)
260 for _, value := range enum.Values {
261 duplicate := ""
262 if _, present := generated[value.Desc.Number()]; present {
263 duplicate = "// Duplicate value: "
264 }
265 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
266 generated[value.Desc.Number()] = true
267 }
268 g.P("}")
269 g.P()
270 valueMap := enum.GoIdent.GoName + "_value"
271 g.P("var ", valueMap, " = map[string]int32{")
272 for _, value := range enum.Values {
273 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
274 }
275 g.P("}")
276 g.P()
277 if enum.Desc.Syntax() != protoreflect.Proto3 {
278 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
279 g.P("p := new(", enum.GoIdent, ")")
280 g.P("*p = x")
281 g.P("return p")
282 g.P("}")
283 g.P()
284 }
285 g.P("func (x ", enum.GoIdent, ") String() string {")
286 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
287 g.P("}")
288 g.P()
289
290 if enum.Desc.Syntax() != protoreflect.Proto3 {
291 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
292 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
293 g.P("if err != nil {")
294 g.P("return err")
295 g.P("}")
296 g.P("*x = ", enum.GoIdent, "(value)")
297 g.P("return nil")
298 g.P("}")
299 g.P()
300 }
301
302 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700303 for i := 1; i < len(enum.Location.Path); i += 2 {
304 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700305 }
306 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
307 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
308 g.P("}")
309 g.P()
310
Damien Neilea7baf42018-09-28 14:23:44 -0700311 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700312}
313
Damien Neil658051b2018-09-10 12:26:21 -0700314// enumRegistryName returns the name used to register an enum with the proto
315// package registry.
316//
317// Confusingly, this is <proto_package>.<go_ident>. This probably should have
318// been the full name of the proto enum type instead, but changing it at this
319// point would require thought.
320func enumRegistryName(enum *protogen.Enum) string {
321 // Find the FileDescriptor for this enum.
322 var desc protoreflect.Descriptor = enum.Desc
323 for {
324 p, ok := desc.Parent()
325 if !ok {
326 break
327 }
328 desc = p
329 }
330 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700331 if fdesc.Package() == "" {
332 return enum.GoIdent.GoName
333 }
Damien Neil658051b2018-09-10 12:26:21 -0700334 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
335}
336
Damien Neild39efc82018-09-24 12:38:10 -0700337func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700338 if message.Desc.IsMapEntry() {
339 return
340 }
341
Damien Neilba1159f2018-10-17 12:53:18 -0700342 hasComment := g.PrintLeadingComments(message.Location)
Damien Neil204f1c02018-10-23 15:03:38 -0700343 if message.Desc.Options().(*descpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700344 if hasComment {
345 g.P("//")
346 }
347 g.P(deprecationComment(true))
348 }
Damien Neil162c1272018-10-04 12:42:37 -0700349 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700350 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700351 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700352 if field.OneofType != nil {
353 // It would be a bit simpler to iterate over the oneofs below,
354 // but generating the field here keeps the contents of the Go
355 // struct in the same order as the contents of the source
356 // .proto file.
357 if field == field.OneofType.Fields[0] {
358 genOneofField(gen, g, f, message, field.OneofType)
359 }
Damien Neil658051b2018-09-10 12:26:21 -0700360 continue
361 }
Damien Neilba1159f2018-10-17 12:53:18 -0700362 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700363 goType, pointer := fieldGoType(g, field)
364 if pointer {
365 goType = "*" + goType
366 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700367 tags := []string{
368 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
369 fmt.Sprintf("json:%q", fieldJSONTag(field)),
370 }
371 if field.Desc.IsMap() {
372 key := field.MessageType.Fields[0]
373 val := field.MessageType.Fields[1]
374 tags = append(tags,
375 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
376 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
377 )
378 }
Damien Neil162c1272018-10-04 12:42:37 -0700379 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700380 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Damien Neil204f1c02018-10-23 15:03:38 -0700381 deprecationComment(field.Desc.Options().(*descpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700382 }
383 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700384
385 if message.Desc.ExtensionRanges().Len() > 0 {
386 var tags []string
Damien Neil204f1c02018-10-23 15:03:38 -0700387 if message.Desc.Options().(*descpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700388 tags = append(tags, `protobuf_messageset:"1"`)
389 }
390 tags = append(tags, `json:"-"`)
391 g.P(protogen.GoIdent{
392 GoImportPath: protoPackage,
393 GoName: "XXX_InternalExtensions",
394 }, " `", strings.Join(tags, " "), "`")
395 }
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
405 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
406 GoImportPath: protoPackage,
407 GoName: "CompactTextString",
408 }, "(m) }")
409 // ProtoMessage
410 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
411 // Descriptor
412 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700413 for i := 1; i < len(message.Location.Path); i += 2 {
414 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700415 }
416 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
417 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
418 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700419 g.P()
420
421 // ExtensionRangeArray
422 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Damien Neil204f1c02018-10-23 15:03:38 -0700423 if message.Desc.Options().(*descpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700424 g.P("func (m *", message.GoIdent, ") MarshalJSON() ([]byte, error) {")
425 g.P("return ", protogen.GoIdent{
426 GoImportPath: protoPackage,
427 GoName: "MarshalMessageSetJSON",
428 }, "(&m.XXX_InternalExtensions)")
429 g.P("}")
430 g.P("func (m *", message.GoIdent, ") UnmarshalJSON(buf []byte) error {")
431 g.P("return ", protogen.GoIdent{
432 GoImportPath: protoPackage,
433 GoName: "UnmarshalMessageSetJSON",
434 }, "(buf, &m.XXX_InternalExtensions)")
435 g.P("}")
436 g.P()
437 }
438
439 protoExtRange := protogen.GoIdent{
440 GoImportPath: protoPackage,
441 GoName: "ExtensionRange",
442 }
443 extRangeVar := "extRange_" + message.GoIdent.GoName
444 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
445 for i := 0; i < extranges.Len(); i++ {
446 r := extranges.Get(i)
447 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
448 }
449 g.P("}")
450 g.P()
451 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
452 g.P("return ", extRangeVar)
453 g.P("}")
454 g.P()
455 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700456
Damien Neilea7baf42018-09-28 14:23:44 -0700457 genWellKnownType(g, "*", message.GoIdent, message.Desc)
458
Damien Neila1c6abc2018-09-12 13:36:34 -0700459 // Table-driven proto support.
460 //
461 // TODO: It does not scale to keep adding another method for every
462 // operation on protos that we want to switch over to using the
463 // table-driven approach. Instead, we should only add a single method
464 // that allows getting access to the *InternalMessageInfo struct and then
465 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
466 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
467 // XXX_Unmarshal
468 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
469 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
470 g.P("}")
471 // XXX_Marshal
472 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
473 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
474 g.P("}")
475 // XXX_Merge
476 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
477 g.P(messageInfoVar, ".Merge(m, src)")
478 g.P("}")
479 // XXX_Size
480 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
481 g.P("return ", messageInfoVar, ".Size(m)")
482 g.P("}")
483 // XXX_DiscardUnknown
484 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
485 g.P(messageInfoVar, ".DiscardUnknown(m)")
486 g.P("}")
487 g.P()
488 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
489 GoImportPath: protoPackage,
490 GoName: "InternalMessageInfo",
491 })
492 g.P()
493
Damien Neilebc699d2018-09-13 08:50:13 -0700494 // Constants and vars holding the default values of fields.
495 for _, field := range message.Fields {
Damien Neilccf3fa62018-09-28 14:41:45 -0700496 if !fieldHasDefault(field) {
Damien Neilebc699d2018-09-13 08:50:13 -0700497 continue
498 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700499 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700500 def := field.Desc.Default()
501 switch field.Desc.Kind() {
502 case protoreflect.StringKind:
503 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
504 case protoreflect.BytesKind:
505 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
506 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700507 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700508 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700509 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700510 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
511 case protoreflect.FloatKind, protoreflect.DoubleKind:
512 // Floating point numbers need extra handling for -Inf/Inf/NaN.
513 f := field.Desc.Default().Float()
514 goType := "float64"
515 if field.Desc.Kind() == protoreflect.FloatKind {
516 goType = "float32"
517 }
518 // funcCall returns a call to a function in the math package,
519 // possibly converting the result to float32.
520 funcCall := func(fn, param string) string {
521 s := g.QualifiedGoIdent(protogen.GoIdent{
522 GoImportPath: "math",
523 GoName: fn,
524 }) + param
525 if goType != "float64" {
526 s = goType + "(" + s + ")"
527 }
528 return s
529 }
530 switch {
531 case math.IsInf(f, -1):
532 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
533 case math.IsInf(f, 1):
534 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
535 case math.IsNaN(f):
536 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
537 default:
Damien Neil982684b2018-09-28 14:12:41 -0700538 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700539 }
540 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700541 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700542 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
543 }
544 }
545 g.P()
546
Damien Neil77f82fe2018-09-13 10:59:17 -0700547 // Getters.
548 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700549 if field.OneofType != nil {
550 if field == field.OneofType.Fields[0] {
551 genOneofTypes(gen, g, f, message, field.OneofType)
552 }
553 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700554 goType, pointer := fieldGoType(g, field)
555 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil204f1c02018-10-23 15:03:38 -0700556 if field.Desc.Options().(*descpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700557 g.P(deprecationComment(true))
558 }
Damien Neil162c1272018-10-04 12:42:37 -0700559 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700560 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
561 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700562 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700563 g.P("return x.", field.GoName)
564 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700565 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700566 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
567 g.P("if m != nil {")
568 } else {
569 g.P("if m != nil && m.", field.GoName, " != nil {")
570 }
571 star := ""
572 if pointer {
573 star = "*"
574 }
575 g.P("return ", star, " m.", field.GoName)
576 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700577 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700578 g.P("return ", defaultValue)
579 g.P("}")
580 g.P()
581 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700582
Damien Neil1fa78d82018-09-13 13:12:36 -0700583 if len(message.Oneofs) > 0 {
584 genOneofFuncs(gen, g, f, message)
585 }
Damien Neil993c04d2018-09-14 15:41:11 -0700586 for _, extension := range message.Extensions {
587 genExtension(gen, g, f, extension)
588 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700589}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700590
Damien Neil77f82fe2018-09-13 10:59:17 -0700591// fieldGoType returns the Go type used for a field.
592//
593// If it returns pointer=true, the struct field is a pointer to the type.
594func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700595 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700596 switch field.Desc.Kind() {
597 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700598 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700599 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700600 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700601 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700602 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700603 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700604 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700605 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700606 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700607 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700608 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700609 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700610 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700611 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700612 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700613 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700615 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 goType = "[]byte"
617 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700618 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700619 if field.Desc.IsMap() {
620 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
621 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
622 return fmt.Sprintf("map[%v]%v", keyType, valType), false
623 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
625 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700626 }
627 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 goType = "[]" + goType
629 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700630 }
Damien Neil44000a12018-10-24 12:31:16 -0700631 // Extension fields always have pointer type, even when defined in a proto3 file.
632 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700633 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700634 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700635 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700636}
637
638func fieldProtobufTag(field *protogen.Field) string {
639 var tag []string
640 // wire type
641 tag = append(tag, wireTypes[field.Desc.Kind()])
642 // field number
643 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
644 // cardinality
645 switch field.Desc.Cardinality() {
646 case protoreflect.Optional:
647 tag = append(tag, "opt")
648 case protoreflect.Required:
649 tag = append(tag, "req")
650 case protoreflect.Repeated:
651 tag = append(tag, "rep")
652 }
Damien Neild4803f52018-09-19 11:43:35 -0700653 if field.Desc.IsPacked() {
654 tag = append(tag, "packed")
655 }
Damien Neil658051b2018-09-10 12:26:21 -0700656 // TODO: packed
657 // name
658 name := string(field.Desc.Name())
659 if field.Desc.Kind() == protoreflect.GroupKind {
660 // The name of the FieldDescriptor for a group field is
661 // lowercased. To find the original capitalization, we
662 // look in the field's MessageType.
663 name = string(field.MessageType.Desc.Name())
664 }
665 tag = append(tag, "name="+name)
666 // JSON name
667 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
668 tag = append(tag, "json="+jsonName)
669 }
670 // proto3
Damien Neil44000a12018-10-24 12:31:16 -0700671 // The previous implementation does not tag extension fields as proto3,
672 // even when the field is defined in a proto3 file. Match that behavior
673 // for consistency.
674 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil658051b2018-09-10 12:26:21 -0700675 tag = append(tag, "proto3")
676 }
677 // enum
678 if field.Desc.Kind() == protoreflect.EnumKind {
679 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
680 }
681 // oneof
682 if field.Desc.OneofType() != nil {
683 tag = append(tag, "oneof")
684 }
Damien Neilebc699d2018-09-13 08:50:13 -0700685 // default value
686 // This must appear last in the tag, since commas in strings aren't escaped.
687 if field.Desc.HasDefault() {
688 var def string
689 switch field.Desc.Kind() {
690 case protoreflect.BoolKind:
691 if field.Desc.Default().Bool() {
692 def = "1"
693 } else {
694 def = "0"
695 }
696 case protoreflect.BytesKind:
Joe Tsaibda671f2018-10-20 13:15:35 -0700697 // Preserve protoc-gen-go's historical output of escaped bytes.
698 // This behavior is buggy, but fixing it makes it impossible to
699 // distinguish between the escaped and unescaped forms.
700 //
701 // To match the exact output of protoc, this is identical to the
702 // CEscape function in strutil.cc of the protoc source code.
703 var b []byte
704 for _, c := range field.Desc.Default().Bytes() {
705 switch c {
706 case '\n':
707 b = append(b, `\n`...)
708 case '\r':
709 b = append(b, `\r`...)
710 case '\t':
711 b = append(b, `\t`...)
712 case '"':
713 b = append(b, `\"`...)
714 case '\'':
715 b = append(b, `\'`...)
716 case '\\':
717 b = append(b, `\\`...)
718 default:
719 if c >= 0x20 && c <= 0x7e {
720 b = append(b, c)
721 } else {
722 b = append(b, fmt.Sprintf(`\%03o`, c)...)
723 }
724 }
725 }
726 def = string(b)
Damien Neilebc699d2018-09-13 08:50:13 -0700727 case protoreflect.FloatKind, protoreflect.DoubleKind:
728 f := field.Desc.Default().Float()
729 switch {
730 case math.IsInf(f, -1):
731 def = "-inf"
732 case math.IsInf(f, 1):
733 def = "inf"
734 case math.IsNaN(f):
735 def = "nan"
736 default:
Damien Neil982684b2018-09-28 14:12:41 -0700737 def = fmt.Sprint(field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700738 }
739 default:
740 def = fmt.Sprint(field.Desc.Default().Interface())
741 }
742 tag = append(tag, "def="+def)
743 }
Damien Neil658051b2018-09-10 12:26:21 -0700744 return strings.Join(tag, ",")
745}
746
Damien Neil77f82fe2018-09-13 10:59:17 -0700747func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
748 if field.Desc.Cardinality() == protoreflect.Repeated {
749 return "nil"
750 }
Damien Neilccf3fa62018-09-28 14:41:45 -0700751 if fieldHasDefault(field) {
Damien Neil1fa78d82018-09-13 13:12:36 -0700752 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700753 if field.Desc.Kind() == protoreflect.BytesKind {
754 return "append([]byte(nil), " + defVarName + "...)"
755 }
756 return defVarName
757 }
758 switch field.Desc.Kind() {
759 case protoreflect.BoolKind:
760 return "false"
761 case protoreflect.StringKind:
762 return `""`
763 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
764 return "nil"
765 case protoreflect.EnumKind:
766 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
767 default:
768 return "0"
769 }
770}
771
Damien Neilccf3fa62018-09-28 14:41:45 -0700772// fieldHasDefault returns true if we consider a field to have a default value.
773//
774// For consistency with the previous generator, it returns false for fields with
775// [default=""], preventing the generation of a default const or var for these
776// fields.
777//
778// TODO: Drop this special case.
779func fieldHasDefault(field *protogen.Field) bool {
780 if !field.Desc.HasDefault() {
781 return false
782 }
783 switch field.Desc.Kind() {
784 case protoreflect.StringKind:
785 return field.Desc.Default().String() != ""
786 case protoreflect.BytesKind:
787 return len(field.Desc.Default().Bytes()) > 0
788 }
789 return true
790}
791
Damien Neil658051b2018-09-10 12:26:21 -0700792var wireTypes = map[protoreflect.Kind]string{
793 protoreflect.BoolKind: "varint",
794 protoreflect.EnumKind: "varint",
795 protoreflect.Int32Kind: "varint",
796 protoreflect.Sint32Kind: "zigzag32",
797 protoreflect.Uint32Kind: "varint",
798 protoreflect.Int64Kind: "varint",
799 protoreflect.Sint64Kind: "zigzag64",
800 protoreflect.Uint64Kind: "varint",
801 protoreflect.Sfixed32Kind: "fixed32",
802 protoreflect.Fixed32Kind: "fixed32",
803 protoreflect.FloatKind: "fixed32",
804 protoreflect.Sfixed64Kind: "fixed64",
805 protoreflect.Fixed64Kind: "fixed64",
806 protoreflect.DoubleKind: "fixed64",
807 protoreflect.StringKind: "bytes",
808 protoreflect.BytesKind: "bytes",
809 protoreflect.MessageKind: "bytes",
810 protoreflect.GroupKind: "group",
811}
812
813func fieldJSONTag(field *protogen.Field) string {
814 return string(field.Desc.Name()) + ",omitempty"
815}
816
Damien Neild39efc82018-09-24 12:38:10 -0700817func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700818 // Special case for proto2 message sets: If this extension is extending
819 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
820 // then drop that last component.
821 //
822 // TODO: This should be implemented in the text formatter rather than the generator.
823 // In addition, the situation for when to apply this special case is implemented
824 // differently in other languages:
825 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
826 name := extension.Desc.FullName()
827 if isExtensionMessageSetElement(gen, extension) {
828 name = name.Parent()
829 }
830
Damien Neil6b541312018-10-29 09:14:14 -0700831 g.P("var ", extensionVar(f.File, extension), " = &", protogen.GoIdent{
Damien Neil993c04d2018-09-14 15:41:11 -0700832 GoImportPath: protoPackage,
833 GoName: "ExtensionDesc",
834 }, "{")
835 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
836 goType, pointer := fieldGoType(g, extension)
837 if pointer {
838 goType = "*" + goType
839 }
840 g.P("ExtensionType: (", goType, ")(nil),")
841 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700842 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700843 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
844 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
845 g.P("}")
846 g.P()
847}
848
Damien Neil154da982018-09-19 13:21:58 -0700849func isExtensionMessageSetElement(gen *protogen.Plugin, extension *protogen.Extension) bool {
850 return extension.ParentMessage != nil &&
Damien Neil204f1c02018-10-23 15:03:38 -0700851 extension.ExtendedType.Desc.Options().(*descpb.MessageOptions).GetMessageSetWireFormat() &&
Damien Neil154da982018-09-19 13:21:58 -0700852 extension.Desc.Name() == "message_set_extension"
853}
854
Damien Neil993c04d2018-09-14 15:41:11 -0700855// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700856func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700857 name := "E_"
858 if extension.ParentMessage != nil {
859 name += extension.ParentMessage.GoIdent.GoName + "_"
860 }
861 name += extension.GoName
862 return protogen.GoIdent{
863 GoImportPath: f.GoImportPath,
864 GoName: name,
865 }
866}
867
Damien Neilce36f8d2018-09-13 15:19:08 -0700868// genInitFunction generates an init function that registers the types in the
869// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700870func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil993c04d2018-09-14 15:41:11 -0700871 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700872 return
873 }
874
875 g.P("func init() {")
Damien Neil154da982018-09-19 13:21:58 -0700876 for _, enum := range f.allEnums {
877 name := enum.GoIdent.GoName
878 g.P(protogen.GoIdent{
879 GoImportPath: protoPackage,
880 GoName: "RegisterEnum",
881 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
882 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700883 for _, message := range f.allMessages {
884 if message.Desc.IsMapEntry() {
885 continue
886 }
887
Damien Neil154da982018-09-19 13:21:58 -0700888 for _, extension := range message.Extensions {
889 genRegisterExtension(gen, g, f, extension)
890 }
891
Damien Neilce36f8d2018-09-13 15:19:08 -0700892 name := message.GoIdent.GoName
893 g.P(protogen.GoIdent{
894 GoImportPath: protoPackage,
895 GoName: "RegisterType",
896 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
897
898 // Types of map fields, sorted by the name of the field message type.
899 var mapFields []*protogen.Field
900 for _, field := range message.Fields {
901 if field.Desc.IsMap() {
902 mapFields = append(mapFields, field)
903 }
904 }
905 sort.Slice(mapFields, func(i, j int) bool {
906 ni := mapFields[i].MessageType.Desc.FullName()
907 nj := mapFields[j].MessageType.Desc.FullName()
908 return ni < nj
909 })
910 for _, field := range mapFields {
911 typeName := string(field.MessageType.Desc.FullName())
912 goType, _ := fieldGoType(g, field)
913 g.P(protogen.GoIdent{
914 GoImportPath: protoPackage,
915 GoName: "RegisterMapType",
916 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
917 }
918 }
Damien Neil154da982018-09-19 13:21:58 -0700919 for _, extension := range f.Extensions {
920 genRegisterExtension(gen, g, f, extension)
Damien Neil993c04d2018-09-14 15:41:11 -0700921 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700922 g.P("}")
923 g.P()
924}
925
Damien Neild39efc82018-09-24 12:38:10 -0700926func genRegisterExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700927 g.P(protogen.GoIdent{
928 GoImportPath: protoPackage,
929 GoName: "RegisterExtension",
Damien Neil6b541312018-10-29 09:14:14 -0700930 }, "(", extensionVar(f.File, extension), ")")
Damien Neil154da982018-09-19 13:21:58 -0700931 if isExtensionMessageSetElement(gen, extension) {
932 goType, pointer := fieldGoType(g, extension)
933 if pointer {
934 goType = "*" + goType
935 }
936 g.P(protogen.GoIdent{
937 GoImportPath: protoPackage,
938 GoName: "RegisterMessageSetType",
939 }, "((", goType, ")(nil), ", extension.Desc.Number(), ",", strconv.Quote(string(extension.Desc.FullName().Parent())), ")")
940 }
941}
942
Damien Neil55fe1c02018-09-17 15:11:24 -0700943// deprecationComment returns a standard deprecation comment if deprecated is true.
944func deprecationComment(deprecated bool) string {
945 if !deprecated {
946 return ""
947 }
948 return "// Deprecated: Do not use."
949}
950
Damien Neilea7baf42018-09-28 14:23:44 -0700951func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700952 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700953 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700954 g.P()
955 }
956}
957
958// Names of messages and enums for which we will generate XXX_WellKnownType methods.
959var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700960 "google.protobuf.Any": true,
961 "google.protobuf.Duration": true,
962 "google.protobuf.Empty": true,
963 "google.protobuf.Struct": true,
964 "google.protobuf.Timestamp": true,
965
966 "google.protobuf.BoolValue": true,
967 "google.protobuf.BytesValue": true,
968 "google.protobuf.DoubleValue": true,
969 "google.protobuf.FloatValue": true,
970 "google.protobuf.Int32Value": true,
971 "google.protobuf.Int64Value": true,
972 "google.protobuf.ListValue": true,
973 "google.protobuf.NullValue": true,
974 "google.protobuf.StringValue": true,
975 "google.protobuf.UInt32Value": true,
976 "google.protobuf.UInt64Value": true,
977 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700978}