blob: 2a53d950d0073e4cac44e354a48a4aeb52157cd1 [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"
Joe Tsai05828db2018-11-01 13:52:16 -070020 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai01ab2962018-09-21 17:44:00 -070021 "github.com/golang/protobuf/v2/protogen"
22 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080023
24 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070025)
26
Damien Neild4127922018-09-12 11:13:49 -070027// generatedCodeVersion indicates a version of the generated code.
28// It is incremented whenever an incompatibility between the generated code and
29// proto package is introduced; the generated code references
30// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
Joe Tsaid7e97bc2018-11-26 12:57:27 -080031const generatedCodeVersion = 3
Damien Neild4127922018-09-12 11:13:49 -070032
Joe Tsaic1c17aa2018-11-16 11:14:14 -080033const (
34 fmtPackage = protogen.GoImportPath("fmt")
35 mathPackage = protogen.GoImportPath("math")
36 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
37)
Damien Neil46abb572018-09-07 12:45:37 -070038
Damien Neild39efc82018-09-24 12:38:10 -070039type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070040 *protogen.File
Damien Neil46abb572018-09-07 12:45:37 -070041 descriptorVar string // var containing the gzipped FileDescriptorProto
Damien Neilce36f8d2018-09-13 15:19:08 -070042 allEnums []*protogen.Enum
43 allMessages []*protogen.Message
Damien Neil993c04d2018-09-14 15:41:11 -070044 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070045}
46
Damien Neil9c420a62018-09-27 15:26:33 -070047// GenerateFile generates the contents of a .pb.go file.
48func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070049 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070050 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070051 }
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
Damien Neilba1159f2018-10-17 12:53:18 -070079 g.PrintLeadingComments(protogen.Location{
80 SourceFile: f.Proto.GetName(),
81 Path: []int32{filePackageField},
82 })
Damien Neilcab8dfe2018-09-06 14:51:28 -070083 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070084 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070085 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -070086
87 // These references are not necessary, since we automatically add
88 // all necessary imports before formatting the generated file.
89 //
90 // This section exists to generate output more consistent with
91 // the previous version of protoc-gen-go, to make it easier to
92 // detect unintended variations.
93 //
94 // TODO: Eventually remove this.
95 g.P("// Reference imports to suppress errors if they are not otherwise used.")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080096 g.P("var _ = ", protoPackage.Ident("Marshal"))
97 g.P("var _ = ", fmtPackage.Ident("Errorf"))
98 g.P("var _ = ", mathPackage.Ident("Inf"))
Damien Neil1ec33152018-09-13 13:12:36 -070099 g.P()
100
Damien Neild4127922018-09-12 11:13:49 -0700101 g.P("// This is a compile-time assertion to ensure that this generated file")
102 g.P("// is compatible with the proto package it is being compiled against.")
103 g.P("// A compilation error at this line likely means your copy of the")
104 g.P("// proto package needs to be updated.")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800105 g.P("const _ = ", protoPackage.Ident(fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion)),
106 "// please upgrade the proto package")
Damien Neild4127922018-09-12 11:13:49 -0700107 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700108
Damien Neil73ac8852018-09-17 15:11:24 -0700109 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
110 genImport(gen, g, f, imps.Get(i))
111 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700112 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700113 genEnum(gen, g, f, enum)
114 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700115 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700116 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700117 }
Damien Neil993c04d2018-09-14 15:41:11 -0700118 for _, extension := range f.Extensions {
119 genExtension(gen, g, f, extension)
120 }
Damien Neil220c2022018-08-15 11:24:18 -0700121
Damien Neilce36f8d2018-09-13 15:19:08 -0700122 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700123 genFileDescriptor(gen, g, f)
124}
125
Damien Neil73ac8852018-09-17 15:11:24 -0700126// walkMessages calls f on each message and all of its descendants.
127func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
128 for _, m := range messages {
129 f(m)
130 walkMessages(m.Messages, f)
131 }
132}
133
Damien Neild39efc82018-09-24 12:38:10 -0700134func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700135 impFile, ok := gen.FileByName(imp.Path())
136 if !ok {
137 return
138 }
139 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700140 // Don't generate imports or aliases for types in the same Go package.
141 return
142 }
Damien Neil40a08052018-10-29 09:07:41 -0700143 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700144 // referenced, because other code and tools depend on having the
145 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700146 if !imp.IsWeak {
147 g.Import(impFile.GoImportPath)
148 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700149 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700150 return
151 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700152 // TODO: An alternate approach to generating public imports might be
153 // to generate the imported file contents, parse it, and extract all
154 // exported identifiers from the AST to build a list of forwarding
155 // declarations.
156 //
157 // TODO: Consider whether this should generate recursive aliases. e.g.,
158 // if a.proto publicly imports b.proto publicly imports c.proto, should
159 // a.pb.go contain aliases for symbols defined in c.proto?
Damien Neil73ac8852018-09-17 15:11:24 -0700160 var enums []*protogen.Enum
161 enums = append(enums, impFile.Enums...)
162 walkMessages(impFile.Messages, func(message *protogen.Message) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700163 if message.Desc.IsMapEntry() {
164 return
165 }
Damien Neil73ac8852018-09-17 15:11:24 -0700166 enums = append(enums, message.Enums...)
Damien Neil2193e8d2018-10-09 12:49:13 -0700167 for _, field := range message.Fields {
168 if !fieldHasDefault(field) {
169 continue
170 }
171 defVar := protogen.GoIdent{
172 GoImportPath: message.GoIdent.GoImportPath,
173 GoName: "Default_" + message.GoIdent.GoName + "_" + field.GoName,
174 }
175 decl := "const"
Damien Neil7e5c6472018-11-29 08:57:07 -0800176 switch field.Desc.Kind() {
177 case protoreflect.BytesKind:
Damien Neil2193e8d2018-10-09 12:49:13 -0700178 decl = "var"
Damien Neil7e5c6472018-11-29 08:57:07 -0800179 case protoreflect.FloatKind, protoreflect.DoubleKind:
180 f := field.Desc.Default().Float()
181 if math.IsInf(f, -1) || math.IsInf(f, 1) || math.IsNaN(f) {
182 decl = "var"
183 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700184 }
185 g.P(decl, " ", defVar.GoName, " = ", defVar)
186 }
Damien Neil73ac8852018-09-17 15:11:24 -0700187 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
188 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
189 for _, oneof := range message.Oneofs {
190 for _, field := range oneof.Fields {
191 typ := fieldOneofType(field)
192 g.P("type ", typ.GoName, " = ", typ)
193 }
194 }
195 g.P()
196 })
197 for _, enum := range enums {
198 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
199 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
200 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
201 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
202 g.P()
203 for _, value := range enum.Values {
204 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
205 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700206 }
Damien Neil6b541312018-10-29 09:14:14 -0700207 for _, ext := range impFile.Extensions {
208 ident := extensionVar(impFile, ext)
209 g.P("var ", ident.GoName, " = ", ident)
210 g.P()
211 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700212 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700213}
214
Damien Neild39efc82018-09-24 12:38:10 -0700215func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700216 // Trim the source_code_info from the descriptor.
217 // Marshal and gzip it.
Joe Tsaie1f8d502018-11-26 18:55:29 -0800218 descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto)
Damien Neil7779e052018-09-07 14:14:06 -0700219 descProto.SourceCodeInfo = nil
220 b, err := proto.Marshal(descProto)
221 if err != nil {
222 gen.Error(err)
223 return
224 }
225 var buf bytes.Buffer
226 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
227 w.Write(b)
228 w.Close()
229 b = buf.Bytes()
230
Damien Neil46abb572018-09-07 12:45:37 -0700231 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700232 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700233 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700234 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
235 for len(b) > 0 {
236 n := 16
237 if n > len(b) {
238 n = len(b)
239 }
240
241 s := ""
242 for _, c := range b[:n] {
243 s += fmt.Sprintf("0x%02x,", c)
244 }
245 g.P(s)
246
247 b = b[n:]
248 }
249 g.P("}")
250 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700251}
Damien Neilc7d07d92018-08-22 13:46:02 -0700252
Damien Neild39efc82018-09-24 12:38:10 -0700253func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700254 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700255 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700256 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800257 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700258 g.P("const (")
259 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700260 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700261 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700262 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800263 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700264 }
265 g.P(")")
266 g.P()
267 nameMap := enum.GoIdent.GoName + "_name"
268 g.P("var ", nameMap, " = map[int32]string{")
269 generated := make(map[protoreflect.EnumNumber]bool)
270 for _, value := range enum.Values {
271 duplicate := ""
272 if _, present := generated[value.Desc.Number()]; present {
273 duplicate = "// Duplicate value: "
274 }
275 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
276 generated[value.Desc.Number()] = true
277 }
278 g.P("}")
279 g.P()
280 valueMap := enum.GoIdent.GoName + "_value"
281 g.P("var ", valueMap, " = map[string]int32{")
282 for _, value := range enum.Values {
283 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
284 }
285 g.P("}")
286 g.P()
287 if enum.Desc.Syntax() != protoreflect.Proto3 {
288 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
289 g.P("p := new(", enum.GoIdent, ")")
290 g.P("*p = x")
291 g.P("return p")
292 g.P("}")
293 g.P()
294 }
295 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800296 g.P("return ", protoPackage.Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700297 g.P("}")
298 g.P()
299
300 if enum.Desc.Syntax() != protoreflect.Proto3 {
301 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800302 g.P("value, err := ", protoPackage.Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700303 g.P("if err != nil {")
304 g.P("return err")
305 g.P("}")
306 g.P("*x = ", enum.GoIdent, "(value)")
307 g.P("return nil")
308 g.P("}")
309 g.P()
310 }
311
312 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700313 for i := 1; i < len(enum.Location.Path); i += 2 {
314 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700315 }
316 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
317 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
318 g.P("}")
319 g.P()
320
Damien Neilea7baf42018-09-28 14:23:44 -0700321 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700322}
323
Damien Neil658051b2018-09-10 12:26:21 -0700324// enumRegistryName returns the name used to register an enum with the proto
325// package registry.
326//
327// Confusingly, this is <proto_package>.<go_ident>. This probably should have
328// been the full name of the proto enum type instead, but changing it at this
329// point would require thought.
330func enumRegistryName(enum *protogen.Enum) string {
331 // Find the FileDescriptor for this enum.
332 var desc protoreflect.Descriptor = enum.Desc
333 for {
334 p, ok := desc.Parent()
335 if !ok {
336 break
337 }
338 desc = p
339 }
340 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700341 if fdesc.Package() == "" {
342 return enum.GoIdent.GoName
343 }
Damien Neil658051b2018-09-10 12:26:21 -0700344 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
345}
346
Damien Neild39efc82018-09-24 12:38:10 -0700347func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700348 if message.Desc.IsMapEntry() {
349 return
350 }
351
Damien Neilba1159f2018-10-17 12:53:18 -0700352 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800353 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700354 if hasComment {
355 g.P("//")
356 }
357 g.P(deprecationComment(true))
358 }
Damien Neil162c1272018-10-04 12:42:37 -0700359 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700360 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700361 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700362 if field.OneofType != nil {
363 // It would be a bit simpler to iterate over the oneofs below,
364 // but generating the field here keeps the contents of the Go
365 // struct in the same order as the contents of the source
366 // .proto file.
367 if field == field.OneofType.Fields[0] {
368 genOneofField(gen, g, f, message, field.OneofType)
369 }
Damien Neil658051b2018-09-10 12:26:21 -0700370 continue
371 }
Damien Neilba1159f2018-10-17 12:53:18 -0700372 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700373 goType, pointer := fieldGoType(g, field)
374 if pointer {
375 goType = "*" + goType
376 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700377 tags := []string{
378 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
379 fmt.Sprintf("json:%q", fieldJSONTag(field)),
380 }
381 if field.Desc.IsMap() {
382 key := field.MessageType.Fields[0]
383 val := field.MessageType.Fields[1]
384 tags = append(tags,
385 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
386 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
387 )
388 }
Damien Neil162c1272018-10-04 12:42:37 -0700389 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700390 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800391 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700392 }
393 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700394
395 if message.Desc.ExtensionRanges().Len() > 0 {
396 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800397 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700398 tags = append(tags, `protobuf_messageset:"1"`)
399 }
400 tags = append(tags, `json:"-"`)
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800401 g.P(protoPackage.Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700402 }
Damien Neil658051b2018-09-10 12:26:21 -0700403 // TODO XXX_InternalExtensions
404 g.P("XXX_unrecognized []byte `json:\"-\"`")
405 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700406 g.P("}")
407 g.P()
408
Damien Neila1c6abc2018-09-12 13:36:34 -0700409 // Reset
410 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
411 // String
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800412 g.P("func (m *", message.GoIdent, ") String() string { return ", protoPackage.Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700413 // ProtoMessage
414 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
415 // Descriptor
416 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700417 for i := 1; i < len(message.Location.Path); i += 2 {
418 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700419 }
420 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
421 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
422 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700423 g.P()
424
425 // ExtensionRangeArray
426 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800427 protoExtRange := protoPackage.Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700428 extRangeVar := "extRange_" + message.GoIdent.GoName
429 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
430 for i := 0; i < extranges.Len(); i++ {
431 r := extranges.Get(i)
432 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
433 }
434 g.P("}")
435 g.P()
436 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
437 g.P("return ", extRangeVar)
438 g.P("}")
439 g.P()
440 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700441
Damien Neilea7baf42018-09-28 14:23:44 -0700442 genWellKnownType(g, "*", message.GoIdent, message.Desc)
443
Damien Neila1c6abc2018-09-12 13:36:34 -0700444 // Table-driven proto support.
445 //
446 // TODO: It does not scale to keep adding another method for every
447 // operation on protos that we want to switch over to using the
448 // table-driven approach. Instead, we should only add a single method
449 // that allows getting access to the *InternalMessageInfo struct and then
450 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
451 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
452 // XXX_Unmarshal
453 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
454 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
455 g.P("}")
456 // XXX_Marshal
457 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
458 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
459 g.P("}")
460 // XXX_Merge
461 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
462 g.P(messageInfoVar, ".Merge(m, src)")
463 g.P("}")
464 // XXX_Size
465 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
466 g.P("return ", messageInfoVar, ".Size(m)")
467 g.P("}")
468 // XXX_DiscardUnknown
469 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
470 g.P(messageInfoVar, ".DiscardUnknown(m)")
471 g.P("}")
472 g.P()
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800473 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
Damien Neila1c6abc2018-09-12 13:36:34 -0700474 g.P()
475
Damien Neilebc699d2018-09-13 08:50:13 -0700476 // Constants and vars holding the default values of fields.
477 for _, field := range message.Fields {
Damien Neilccf3fa62018-09-28 14:41:45 -0700478 if !fieldHasDefault(field) {
Damien Neilebc699d2018-09-13 08:50:13 -0700479 continue
480 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700481 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700482 def := field.Desc.Default()
483 switch field.Desc.Kind() {
484 case protoreflect.StringKind:
485 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
486 case protoreflect.BytesKind:
487 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
488 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700489 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700490 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700491 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700492 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
493 case protoreflect.FloatKind, protoreflect.DoubleKind:
494 // Floating point numbers need extra handling for -Inf/Inf/NaN.
495 f := field.Desc.Default().Float()
496 goType := "float64"
497 if field.Desc.Kind() == protoreflect.FloatKind {
498 goType = "float32"
499 }
500 // funcCall returns a call to a function in the math package,
501 // possibly converting the result to float32.
502 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800503 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700504 if goType != "float64" {
505 s = goType + "(" + s + ")"
506 }
507 return s
508 }
509 switch {
510 case math.IsInf(f, -1):
511 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
512 case math.IsInf(f, 1):
513 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
514 case math.IsNaN(f):
515 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
516 default:
Damien Neil982684b2018-09-28 14:12:41 -0700517 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700518 }
519 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700520 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700521 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
522 }
523 }
524 g.P()
525
Damien Neil77f82fe2018-09-13 10:59:17 -0700526 // Getters.
527 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700528 if field.OneofType != nil {
529 if field == field.OneofType.Fields[0] {
530 genOneofTypes(gen, g, f, message, field.OneofType)
531 }
532 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700533 goType, pointer := fieldGoType(g, field)
534 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800535 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700536 g.P(deprecationComment(true))
537 }
Damien Neil162c1272018-10-04 12:42:37 -0700538 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700539 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
540 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700541 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700542 g.P("return x.", field.GoName)
543 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700544 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700545 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
546 g.P("if m != nil {")
547 } else {
548 g.P("if m != nil && m.", field.GoName, " != nil {")
549 }
550 star := ""
551 if pointer {
552 star = "*"
553 }
554 g.P("return ", star, " m.", field.GoName)
555 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700556 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700557 g.P("return ", defaultValue)
558 g.P("}")
559 g.P()
560 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700561
Damien Neil1fa78d82018-09-13 13:12:36 -0700562 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800563 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700564 }
Damien Neil993c04d2018-09-14 15:41:11 -0700565 for _, extension := range message.Extensions {
566 genExtension(gen, g, f, extension)
567 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700568}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700569
Damien Neil77f82fe2018-09-13 10:59:17 -0700570// fieldGoType returns the Go type used for a field.
571//
572// If it returns pointer=true, the struct field is a pointer to the type.
573func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700574 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700575 switch field.Desc.Kind() {
576 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700577 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700578 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700579 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700580 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700581 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700582 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700583 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700584 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700585 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700586 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700587 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700588 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700589 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700590 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700591 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700592 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700593 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700594 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700595 goType = "[]byte"
596 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700597 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700598 if field.Desc.IsMap() {
599 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
600 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
601 return fmt.Sprintf("map[%v]%v", keyType, valType), false
602 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700603 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
604 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700605 }
606 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700607 goType = "[]" + goType
608 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700609 }
Damien Neil44000a12018-10-24 12:31:16 -0700610 // Extension fields always have pointer type, even when defined in a proto3 file.
611 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700612 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700613 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700615}
616
617func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700618 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700619 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700620 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700621 }
Joe Tsai05828db2018-11-01 13:52:16 -0700622 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700623}
624
Damien Neil77f82fe2018-09-13 10:59:17 -0700625func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
626 if field.Desc.Cardinality() == protoreflect.Repeated {
627 return "nil"
628 }
Damien Neilccf3fa62018-09-28 14:41:45 -0700629 if fieldHasDefault(field) {
Damien Neil1fa78d82018-09-13 13:12:36 -0700630 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700631 if field.Desc.Kind() == protoreflect.BytesKind {
632 return "append([]byte(nil), " + defVarName + "...)"
633 }
634 return defVarName
635 }
636 switch field.Desc.Kind() {
637 case protoreflect.BoolKind:
638 return "false"
639 case protoreflect.StringKind:
640 return `""`
641 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
642 return "nil"
643 case protoreflect.EnumKind:
644 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
645 default:
646 return "0"
647 }
648}
649
Damien Neilccf3fa62018-09-28 14:41:45 -0700650// fieldHasDefault returns true if we consider a field to have a default value.
651//
652// For consistency with the previous generator, it returns false for fields with
653// [default=""], preventing the generation of a default const or var for these
654// fields.
655//
656// TODO: Drop this special case.
657func fieldHasDefault(field *protogen.Field) bool {
658 if !field.Desc.HasDefault() {
659 return false
660 }
661 switch field.Desc.Kind() {
662 case protoreflect.StringKind:
663 return field.Desc.Default().String() != ""
664 case protoreflect.BytesKind:
665 return len(field.Desc.Default().Bytes()) > 0
666 }
667 return true
668}
669
Damien Neil658051b2018-09-10 12:26:21 -0700670func fieldJSONTag(field *protogen.Field) string {
671 return string(field.Desc.Name()) + ",omitempty"
672}
673
Damien Neild39efc82018-09-24 12:38:10 -0700674func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700675 // Special case for proto2 message sets: If this extension is extending
676 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
677 // then drop that last component.
678 //
679 // TODO: This should be implemented in the text formatter rather than the generator.
680 // In addition, the situation for when to apply this special case is implemented
681 // differently in other languages:
682 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
683 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700684 if n, ok := isExtensionMessageSetElement(extension); ok {
685 name = n
Damien Neil154da982018-09-19 13:21:58 -0700686 }
687
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800688 g.P("var ", extensionVar(f.File, extension), " = &", protoPackage.Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700689 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
690 goType, pointer := fieldGoType(g, extension)
691 if pointer {
692 goType = "*" + goType
693 }
694 g.P("ExtensionType: (", goType, ")(nil),")
695 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700696 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700697 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
698 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
699 g.P("}")
700 g.P()
701}
702
Damien Neil62386962018-10-30 10:35:48 -0700703// isExtensionMessageSetELement returns the adjusted name of an extension
704// which extends proto2.bridge.MessageSet.
705func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800706 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700707 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
708 return "", false
709 }
710 if extension.ParentMessage == nil {
711 // This case shouldn't be given special handling at all--we're
712 // only supposed to drop the ".message_set_extension" for
713 // extensions defined within a message (i.e., the extension
714 // takes the message's name).
715 //
716 // This matches the behavior of the v1 generator, however.
717 //
718 // TODO: See if we can drop this case.
719 name = extension.Desc.FullName()
720 name = name[:len(name)-len("message_set_extension")]
721 return name, true
722 }
723 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700724}
725
Damien Neil993c04d2018-09-14 15:41:11 -0700726// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700727func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700728 name := "E_"
729 if extension.ParentMessage != nil {
730 name += extension.ParentMessage.GoIdent.GoName + "_"
731 }
732 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800733 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700734}
735
Damien Neilce36f8d2018-09-13 15:19:08 -0700736// genInitFunction generates an init function that registers the types in the
737// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700738func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil993c04d2018-09-14 15:41:11 -0700739 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700740 return
741 }
742
743 g.P("func init() {")
Damien Neil154da982018-09-19 13:21:58 -0700744 for _, enum := range f.allEnums {
745 name := enum.GoIdent.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800746 g.P(protoPackage.Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700747 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700748 for _, message := range f.allMessages {
749 if message.Desc.IsMapEntry() {
750 continue
751 }
752
Damien Neil154da982018-09-19 13:21:58 -0700753 for _, extension := range message.Extensions {
754 genRegisterExtension(gen, g, f, extension)
755 }
756
Damien Neilce36f8d2018-09-13 15:19:08 -0700757 name := message.GoIdent.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800758 g.P(protoPackage.Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700759
760 // Types of map fields, sorted by the name of the field message type.
761 var mapFields []*protogen.Field
762 for _, field := range message.Fields {
763 if field.Desc.IsMap() {
764 mapFields = append(mapFields, field)
765 }
766 }
767 sort.Slice(mapFields, func(i, j int) bool {
768 ni := mapFields[i].MessageType.Desc.FullName()
769 nj := mapFields[j].MessageType.Desc.FullName()
770 return ni < nj
771 })
772 for _, field := range mapFields {
773 typeName := string(field.MessageType.Desc.FullName())
774 goType, _ := fieldGoType(g, field)
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800775 g.P(protoPackage.Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700776 }
777 }
Damien Neil154da982018-09-19 13:21:58 -0700778 for _, extension := range f.Extensions {
779 genRegisterExtension(gen, g, f, extension)
Damien Neil993c04d2018-09-14 15:41:11 -0700780 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700781 g.P("}")
782 g.P()
783}
784
Damien Neild39efc82018-09-24 12:38:10 -0700785func genRegisterExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800786 g.P(protoPackage.Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil154da982018-09-19 13:21:58 -0700787}
788
Damien Neil55fe1c02018-09-17 15:11:24 -0700789// deprecationComment returns a standard deprecation comment if deprecated is true.
790func deprecationComment(deprecated bool) string {
791 if !deprecated {
792 return ""
793 }
794 return "// Deprecated: Do not use."
795}
796
Damien Neilea7baf42018-09-28 14:23:44 -0700797func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700798 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700799 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700800 g.P()
801 }
802}
803
804// Names of messages and enums for which we will generate XXX_WellKnownType methods.
805var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700806 "google.protobuf.Any": true,
807 "google.protobuf.Duration": true,
808 "google.protobuf.Empty": true,
809 "google.protobuf.Struct": true,
810 "google.protobuf.Timestamp": true,
811
812 "google.protobuf.BoolValue": true,
813 "google.protobuf.BytesValue": true,
814 "google.protobuf.DoubleValue": true,
815 "google.protobuf.FloatValue": true,
816 "google.protobuf.Int32Value": true,
817 "google.protobuf.Int64Value": true,
818 "google.protobuf.ListValue": true,
819 "google.protobuf.NullValue": true,
820 "google.protobuf.StringValue": true,
821 "google.protobuf.UInt32Value": true,
822 "google.protobuf.UInt64Value": true,
823 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700824}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800825
826// genOneofField generates the struct field for a oneof.
827func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
828 if g.PrintLeadingComments(oneof.Location) {
829 g.P("//")
830 }
831 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
832 for _, field := range oneof.Fields {
833 g.PrintLeadingComments(field.Location)
834 g.P("//\t*", fieldOneofType(field))
835 }
836 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
837 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
838}
839
840// genOneofTypes generates the interface type used for a oneof field,
841// and the wrapper types that satisfy that interface.
842//
843// It also generates the getter method for the parent oneof field
844// (but not the member fields).
845func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
846 ifName := oneofInterfaceName(oneof)
847 g.P("type ", ifName, " interface {")
848 g.P(ifName, "()")
849 g.P("}")
850 g.P()
851 for _, field := range oneof.Fields {
852 name := fieldOneofType(field)
853 g.Annotate(name.GoName, field.Location)
854 g.Annotate(name.GoName+"."+field.GoName, field.Location)
855 g.P("type ", name, " struct {")
856 goType, _ := fieldGoType(g, field)
857 tags := []string{
858 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
859 }
860 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
861 g.P("}")
862 g.P()
863 }
864 for _, field := range oneof.Fields {
865 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
866 g.P()
867 }
868 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
869 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
870 g.P("if m != nil {")
871 g.P("return m.", oneofFieldName(oneof))
872 g.P("}")
873 g.P("return nil")
874 g.P("}")
875 g.P()
876}
877
878// oneofFieldName returns the name of the struct field holding the oneof value.
879//
880// This function is trivial, but pulling out the name like this makes it easier
881// to experiment with alternative oneof implementations.
882func oneofFieldName(oneof *protogen.Oneof) string {
883 return oneof.GoName
884}
885
886// oneofInterfaceName returns the name of the interface type implemented by
887// the oneof field value types.
888func oneofInterfaceName(oneof *protogen.Oneof) string {
889 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
890}
891
892// genOneofWrappers generates the XXX_OneofWrappers method for a message.
893func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
894 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
895 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
896 g.P("return []interface{}{")
897 for _, oneof := range message.Oneofs {
898 for _, field := range oneof.Fields {
899 g.P("(*", fieldOneofType(field), ")(nil),")
900 }
901 }
902 g.P("}")
903 g.P("}")
904 g.P()
905}
906
907// fieldOneofType returns the wrapper type used to represent a field in a oneof.
908func fieldOneofType(field *protogen.Field) protogen.GoIdent {
909 ident := protogen.GoIdent{
910 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
911 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
912 }
913 // Check for collisions with nested messages or enums.
914 //
915 // This conflict resolution is incomplete: Among other things, it
916 // does not consider collisions with other oneof field types.
917 //
918 // TODO: Consider dropping this entirely. Detecting conflicts and
919 // producing an error is almost certainly better than permuting
920 // field and type names in mostly unpredictable ways.
921Loop:
922 for {
923 for _, message := range field.ParentMessage.Messages {
924 if message.GoIdent == ident {
925 ident.GoName += "_"
926 continue Loop
927 }
928 }
929 for _, enum := range field.ParentMessage.Enums {
930 if enum.GoIdent == ident {
931 ident.GoName += "_"
932 continue Loop
933 }
934 }
935 return ident
936 }
937}