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