blob: 435eb5be7c04239e9f86e70ba40f019d4da25014 [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
Joe Tsaib6405bd2018-11-15 14:44:37 -080045
46 fileReflect fileReflect
Damien Neilcab8dfe2018-09-06 14:51:28 -070047}
48
Damien Neil9c420a62018-09-27 15:26:33 -070049// GenerateFile generates the contents of a .pb.go file.
50func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070051 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070052 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070053 }
54
Damien Neil993c04d2018-09-14 15:41:11 -070055 // The different order for enums and extensions is to match the output
56 // of the previous implementation.
57 //
Joe Tsaib6405bd2018-11-15 14:44:37 -080058 // TODO: Eventually make this consistent (and remove fileReflect).
Damien Neilce36f8d2018-09-13 15:19:08 -070059 f.allEnums = append(f.allEnums, f.File.Enums...)
Damien Neil73ac8852018-09-17 15:11:24 -070060 walkMessages(f.Messages, func(message *protogen.Message) {
61 f.allMessages = append(f.allMessages, message)
62 f.allEnums = append(f.allEnums, message.Enums...)
63 f.allExtensions = append(f.allExtensions, message.Extensions...)
64 })
Damien Neil993c04d2018-09-14 15:41:11 -070065 f.allExtensions = append(f.allExtensions, f.File.Extensions...)
Damien Neilce36f8d2018-09-13 15:19:08 -070066
Joe Tsaib6405bd2018-11-15 14:44:37 -080067 // Initialize data structures needed for reflection.
68 f.fileReflect.init(f)
69
Damien Neil46abb572018-09-07 12:45:37 -070070 // Determine the name of the var holding the file descriptor:
71 //
72 // fileDescriptor_<hash of filename>
73 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
74 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
75
Damien Neil220c2022018-08-15 11:24:18 -070076 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070077 if f.Proto.GetOptions().GetDeprecated() {
78 g.P("// ", f.Desc.Path(), " is a deprecated file.")
79 } else {
80 g.P("// source: ", f.Desc.Path())
81 }
Damien Neil220c2022018-08-15 11:24:18 -070082 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070083 const filePackageField = 2 // FileDescriptorProto.package
Damien Neilba1159f2018-10-17 12:53:18 -070084 g.PrintLeadingComments(protogen.Location{
85 SourceFile: f.Proto.GetName(),
86 Path: []int32{filePackageField},
87 })
Damien Neilcab8dfe2018-09-06 14:51:28 -070088 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070089 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070090 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -070091
92 // These references are not necessary, since we automatically add
93 // all necessary imports before formatting the generated file.
94 //
95 // This section exists to generate output more consistent with
96 // the previous version of protoc-gen-go, to make it easier to
97 // detect unintended variations.
98 //
99 // TODO: Eventually remove this.
100 g.P("// Reference imports to suppress errors if they are not otherwise used.")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800101 g.P("var _ = ", protoPackage.Ident("Marshal"))
102 g.P("var _ = ", fmtPackage.Ident("Errorf"))
103 g.P("var _ = ", mathPackage.Ident("Inf"))
Damien Neil1ec33152018-09-13 13:12:36 -0700104 g.P()
105
Damien Neild4127922018-09-12 11:13:49 -0700106 g.P("// This is a compile-time assertion to ensure that this generated file")
107 g.P("// is compatible with the proto package it is being compiled against.")
108 g.P("// A compilation error at this line likely means your copy of the")
109 g.P("// proto package needs to be updated.")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800110 g.P("const _ = ", protoPackage.Ident(fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion)),
111 "// please upgrade the proto package")
Damien Neild4127922018-09-12 11:13:49 -0700112 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700113
Damien Neil73ac8852018-09-17 15:11:24 -0700114 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
115 genImport(gen, g, f, imps.Get(i))
116 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700117 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700118 genEnum(gen, g, f, enum)
119 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700120 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700121 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700122 }
Damien Neil993c04d2018-09-14 15:41:11 -0700123 for _, extension := range f.Extensions {
124 genExtension(gen, g, f, extension)
125 }
Damien Neil220c2022018-08-15 11:24:18 -0700126
Damien Neilce36f8d2018-09-13 15:19:08 -0700127 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700128 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800129 genReflectInitFunction(gen, g, f)
130 genReflectFileDescriptor(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700131}
132
Damien Neil73ac8852018-09-17 15:11:24 -0700133// walkMessages calls f on each message and all of its descendants.
134func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
135 for _, m := range messages {
136 f(m)
137 walkMessages(m.Messages, f)
138 }
139}
140
Damien Neild39efc82018-09-24 12:38:10 -0700141func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700142 impFile, ok := gen.FileByName(imp.Path())
143 if !ok {
144 return
145 }
146 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700147 // Don't generate imports or aliases for types in the same Go package.
148 return
149 }
Damien Neil40a08052018-10-29 09:07:41 -0700150 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700151 // referenced, because other code and tools depend on having the
152 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700153 if !imp.IsWeak {
154 g.Import(impFile.GoImportPath)
155 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700156 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700157 return
158 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700159 // TODO: An alternate approach to generating public imports might be
160 // to generate the imported file contents, parse it, and extract all
161 // exported identifiers from the AST to build a list of forwarding
162 // declarations.
163 //
164 // TODO: Consider whether this should generate recursive aliases. e.g.,
165 // if a.proto publicly imports b.proto publicly imports c.proto, should
166 // a.pb.go contain aliases for symbols defined in c.proto?
Damien Neil73ac8852018-09-17 15:11:24 -0700167 var enums []*protogen.Enum
168 enums = append(enums, impFile.Enums...)
169 walkMessages(impFile.Messages, func(message *protogen.Message) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700170 if message.Desc.IsMapEntry() {
171 return
172 }
Damien Neil73ac8852018-09-17 15:11:24 -0700173 enums = append(enums, message.Enums...)
Damien Neil2193e8d2018-10-09 12:49:13 -0700174 for _, field := range message.Fields {
175 if !fieldHasDefault(field) {
176 continue
177 }
178 defVar := protogen.GoIdent{
179 GoImportPath: message.GoIdent.GoImportPath,
180 GoName: "Default_" + message.GoIdent.GoName + "_" + field.GoName,
181 }
182 decl := "const"
Damien Neil7e5c6472018-11-29 08:57:07 -0800183 switch field.Desc.Kind() {
184 case protoreflect.BytesKind:
Damien Neil2193e8d2018-10-09 12:49:13 -0700185 decl = "var"
Damien Neil7e5c6472018-11-29 08:57:07 -0800186 case protoreflect.FloatKind, protoreflect.DoubleKind:
187 f := field.Desc.Default().Float()
188 if math.IsInf(f, -1) || math.IsInf(f, 1) || math.IsNaN(f) {
189 decl = "var"
190 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700191 }
192 g.P(decl, " ", defVar.GoName, " = ", defVar)
193 }
Damien Neil73ac8852018-09-17 15:11:24 -0700194 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
195 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
196 for _, oneof := range message.Oneofs {
197 for _, field := range oneof.Fields {
198 typ := fieldOneofType(field)
199 g.P("type ", typ.GoName, " = ", typ)
200 }
201 }
202 g.P()
203 })
204 for _, enum := range enums {
205 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
206 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
207 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
208 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
209 g.P()
210 for _, value := range enum.Values {
211 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
212 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700213 }
Damien Neil6b541312018-10-29 09:14:14 -0700214 for _, ext := range impFile.Extensions {
215 ident := extensionVar(impFile, ext)
216 g.P("var ", ident.GoName, " = ", ident)
217 g.P()
218 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700219 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700220}
221
Damien Neild39efc82018-09-24 12:38:10 -0700222func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700223 // Trim the source_code_info from the descriptor.
224 // Marshal and gzip it.
Joe Tsaie1f8d502018-11-26 18:55:29 -0800225 descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto)
Damien Neil7779e052018-09-07 14:14:06 -0700226 descProto.SourceCodeInfo = nil
227 b, err := proto.Marshal(descProto)
228 if err != nil {
229 gen.Error(err)
230 return
231 }
232 var buf bytes.Buffer
233 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
234 w.Write(b)
235 w.Close()
236 b = buf.Bytes()
237
Damien Neil46abb572018-09-07 12:45:37 -0700238 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700239 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700240 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700241 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
242 for len(b) > 0 {
243 n := 16
244 if n > len(b) {
245 n = len(b)
246 }
247
248 s := ""
249 for _, c := range b[:n] {
250 s += fmt.Sprintf("0x%02x,", c)
251 }
252 g.P(s)
253
254 b = b[n:]
255 }
256 g.P("}")
257 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700258}
Damien Neilc7d07d92018-08-22 13:46:02 -0700259
Damien Neild39efc82018-09-24 12:38:10 -0700260func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700261 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700262 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700263 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800264 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700265 g.P("const (")
266 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700267 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700268 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700269 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800270 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700271 }
272 g.P(")")
273 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800274
275 // Generate support for protobuf reflection.
276 genReflectEnum(gen, g, f, enum)
277
Damien Neil46abb572018-09-07 12:45:37 -0700278 nameMap := enum.GoIdent.GoName + "_name"
279 g.P("var ", nameMap, " = map[int32]string{")
280 generated := make(map[protoreflect.EnumNumber]bool)
281 for _, value := range enum.Values {
282 duplicate := ""
283 if _, present := generated[value.Desc.Number()]; present {
284 duplicate = "// Duplicate value: "
285 }
286 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
287 generated[value.Desc.Number()] = true
288 }
289 g.P("}")
290 g.P()
291 valueMap := enum.GoIdent.GoName + "_value"
292 g.P("var ", valueMap, " = map[string]int32{")
293 for _, value := range enum.Values {
294 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
295 }
296 g.P("}")
297 g.P()
298 if enum.Desc.Syntax() != protoreflect.Proto3 {
299 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
300 g.P("p := new(", enum.GoIdent, ")")
301 g.P("*p = x")
302 g.P("return p")
303 g.P("}")
304 g.P()
305 }
306 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800307 g.P("return ", protoPackage.Ident("EnumName"), "(", enum.GoIdent, "_name, int32(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700308 g.P("}")
309 g.P()
310
311 if enum.Desc.Syntax() != protoreflect.Proto3 {
312 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800313 g.P("value, err := ", protoPackage.Ident("UnmarshalJSONEnum"), "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
Damien Neil46abb572018-09-07 12:45:37 -0700314 g.P("if err != nil {")
315 g.P("return err")
316 g.P("}")
317 g.P("*x = ", enum.GoIdent, "(value)")
318 g.P("return nil")
319 g.P("}")
320 g.P()
321 }
322
323 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700324 for i := 1; i < len(enum.Location.Path); i += 2 {
325 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700326 }
327 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
328 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
329 g.P("}")
330 g.P()
331
Damien Neilea7baf42018-09-28 14:23:44 -0700332 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700333}
334
Damien Neil658051b2018-09-10 12:26:21 -0700335// enumRegistryName returns the name used to register an enum with the proto
336// package registry.
337//
338// Confusingly, this is <proto_package>.<go_ident>. This probably should have
339// been the full name of the proto enum type instead, but changing it at this
340// point would require thought.
341func enumRegistryName(enum *protogen.Enum) string {
342 // Find the FileDescriptor for this enum.
343 var desc protoreflect.Descriptor = enum.Desc
344 for {
345 p, ok := desc.Parent()
346 if !ok {
347 break
348 }
349 desc = p
350 }
351 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700352 if fdesc.Package() == "" {
353 return enum.GoIdent.GoName
354 }
Damien Neil658051b2018-09-10 12:26:21 -0700355 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
356}
357
Damien Neild39efc82018-09-24 12:38:10 -0700358func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700359 if message.Desc.IsMapEntry() {
360 return
361 }
362
Damien Neilba1159f2018-10-17 12:53:18 -0700363 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800364 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700365 if hasComment {
366 g.P("//")
367 }
368 g.P(deprecationComment(true))
369 }
Damien Neil162c1272018-10-04 12:42:37 -0700370 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700371 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700372 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700373 if field.OneofType != nil {
374 // It would be a bit simpler to iterate over the oneofs below,
375 // but generating the field here keeps the contents of the Go
376 // struct in the same order as the contents of the source
377 // .proto file.
378 if field == field.OneofType.Fields[0] {
379 genOneofField(gen, g, f, message, field.OneofType)
380 }
Damien Neil658051b2018-09-10 12:26:21 -0700381 continue
382 }
Damien Neilba1159f2018-10-17 12:53:18 -0700383 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700384 goType, pointer := fieldGoType(g, field)
385 if pointer {
386 goType = "*" + goType
387 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700388 tags := []string{
389 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
390 fmt.Sprintf("json:%q", fieldJSONTag(field)),
391 }
392 if field.Desc.IsMap() {
393 key := field.MessageType.Fields[0]
394 val := field.MessageType.Fields[1]
395 tags = append(tags,
396 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
397 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
398 )
399 }
Damien Neil162c1272018-10-04 12:42:37 -0700400 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700401 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800402 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700403 }
404 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700405
406 if message.Desc.ExtensionRanges().Len() > 0 {
407 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800408 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700409 tags = append(tags, `protobuf_messageset:"1"`)
410 }
411 tags = append(tags, `json:"-"`)
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800412 g.P(protoPackage.Ident("XXX_InternalExtensions"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700413 }
Damien Neil658051b2018-09-10 12:26:21 -0700414 // TODO XXX_InternalExtensions
415 g.P("XXX_unrecognized []byte `json:\"-\"`")
416 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700417 g.P("}")
418 g.P()
419
Joe Tsaib6405bd2018-11-15 14:44:37 -0800420 // Generate support for protobuf reflection.
421 genReflectMessage(gen, g, f, message)
422
Damien Neila1c6abc2018-09-12 13:36:34 -0700423 // Reset
424 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
425 // String
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800426 g.P("func (m *", message.GoIdent, ") String() string { return ", protoPackage.Ident("CompactTextString"), "(m) }")
Damien Neila1c6abc2018-09-12 13:36:34 -0700427 // ProtoMessage
428 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
429 // Descriptor
430 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700431 for i := 1; i < len(message.Location.Path); i += 2 {
432 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700433 }
434 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
435 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
436 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700437 g.P()
438
439 // ExtensionRangeArray
440 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800441 protoExtRange := protoPackage.Ident("ExtensionRange")
Damien Neil993c04d2018-09-14 15:41:11 -0700442 extRangeVar := "extRange_" + message.GoIdent.GoName
443 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
444 for i := 0; i < extranges.Len(); i++ {
445 r := extranges.Get(i)
446 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
447 }
448 g.P("}")
449 g.P()
450 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
451 g.P("return ", extRangeVar)
452 g.P("}")
453 g.P()
454 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700455
Damien Neilea7baf42018-09-28 14:23:44 -0700456 genWellKnownType(g, "*", message.GoIdent, message.Desc)
457
Damien Neila1c6abc2018-09-12 13:36:34 -0700458 // Table-driven proto support.
459 //
460 // TODO: It does not scale to keep adding another method for every
461 // operation on protos that we want to switch over to using the
462 // table-driven approach. Instead, we should only add a single method
463 // that allows getting access to the *InternalMessageInfo struct and then
464 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
465 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
466 // XXX_Unmarshal
467 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
468 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
469 g.P("}")
470 // XXX_Marshal
471 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
472 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
473 g.P("}")
474 // XXX_Merge
475 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
476 g.P(messageInfoVar, ".Merge(m, src)")
477 g.P("}")
478 // XXX_Size
479 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
480 g.P("return ", messageInfoVar, ".Size(m)")
481 g.P("}")
482 // XXX_DiscardUnknown
483 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
484 g.P(messageInfoVar, ".DiscardUnknown(m)")
485 g.P("}")
486 g.P()
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800487 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
Damien Neila1c6abc2018-09-12 13:36:34 -0700488 g.P()
489
Damien Neilebc699d2018-09-13 08:50:13 -0700490 // Constants and vars holding the default values of fields.
491 for _, field := range message.Fields {
Damien Neilccf3fa62018-09-28 14:41:45 -0700492 if !fieldHasDefault(field) {
Damien Neilebc699d2018-09-13 08:50:13 -0700493 continue
494 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700495 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700496 def := field.Desc.Default()
497 switch field.Desc.Kind() {
498 case protoreflect.StringKind:
499 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
500 case protoreflect.BytesKind:
501 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
502 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700503 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700504 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700505 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700506 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
507 case protoreflect.FloatKind, protoreflect.DoubleKind:
508 // Floating point numbers need extra handling for -Inf/Inf/NaN.
509 f := field.Desc.Default().Float()
510 goType := "float64"
511 if field.Desc.Kind() == protoreflect.FloatKind {
512 goType = "float32"
513 }
514 // funcCall returns a call to a function in the math package,
515 // possibly converting the result to float32.
516 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800517 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700518 if goType != "float64" {
519 s = goType + "(" + s + ")"
520 }
521 return s
522 }
523 switch {
524 case math.IsInf(f, -1):
525 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
526 case math.IsInf(f, 1):
527 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
528 case math.IsNaN(f):
529 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
530 default:
Damien Neil982684b2018-09-28 14:12:41 -0700531 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700532 }
533 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700534 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700535 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
536 }
537 }
538 g.P()
539
Damien Neil77f82fe2018-09-13 10:59:17 -0700540 // Getters.
541 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700542 if field.OneofType != nil {
543 if field == field.OneofType.Fields[0] {
544 genOneofTypes(gen, g, f, message, field.OneofType)
545 }
546 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700547 goType, pointer := fieldGoType(g, field)
548 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800549 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700550 g.P(deprecationComment(true))
551 }
Damien Neil162c1272018-10-04 12:42:37 -0700552 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700553 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
554 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700555 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700556 g.P("return x.", field.GoName)
557 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700558 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700559 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
560 g.P("if m != nil {")
561 } else {
562 g.P("if m != nil && m.", field.GoName, " != nil {")
563 }
564 star := ""
565 if pointer {
566 star = "*"
567 }
568 g.P("return ", star, " m.", field.GoName)
569 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700570 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700571 g.P("return ", defaultValue)
572 g.P("}")
573 g.P()
574 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700575
Damien Neil1fa78d82018-09-13 13:12:36 -0700576 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800577 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700578 }
Damien Neil993c04d2018-09-14 15:41:11 -0700579 for _, extension := range message.Extensions {
580 genExtension(gen, g, f, extension)
581 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700582}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700583
Damien Neil77f82fe2018-09-13 10:59:17 -0700584// fieldGoType returns the Go type used for a field.
585//
586// If it returns pointer=true, the struct field is a pointer to the type.
587func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700588 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700589 switch field.Desc.Kind() {
590 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700591 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700592 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700593 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700594 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700595 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700596 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700597 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700598 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700599 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700600 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700601 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700602 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700603 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700604 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700605 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700606 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700607 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700608 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700609 goType = "[]byte"
610 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700611 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700612 if field.Desc.IsMap() {
613 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
614 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
615 return fmt.Sprintf("map[%v]%v", keyType, valType), false
616 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700617 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
618 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700619 }
620 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700621 goType = "[]" + goType
622 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700623 }
Damien Neil44000a12018-10-24 12:31:16 -0700624 // Extension fields always have pointer type, even when defined in a proto3 file.
625 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700626 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700627 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700629}
630
631func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700632 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700633 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700634 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700635 }
Joe Tsai05828db2018-11-01 13:52:16 -0700636 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700637}
638
Damien Neil77f82fe2018-09-13 10:59:17 -0700639func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
640 if field.Desc.Cardinality() == protoreflect.Repeated {
641 return "nil"
642 }
Damien Neilccf3fa62018-09-28 14:41:45 -0700643 if fieldHasDefault(field) {
Damien Neil1fa78d82018-09-13 13:12:36 -0700644 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700645 if field.Desc.Kind() == protoreflect.BytesKind {
646 return "append([]byte(nil), " + defVarName + "...)"
647 }
648 return defVarName
649 }
650 switch field.Desc.Kind() {
651 case protoreflect.BoolKind:
652 return "false"
653 case protoreflect.StringKind:
654 return `""`
655 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
656 return "nil"
657 case protoreflect.EnumKind:
658 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
659 default:
660 return "0"
661 }
662}
663
Damien Neilccf3fa62018-09-28 14:41:45 -0700664// fieldHasDefault returns true if we consider a field to have a default value.
665//
666// For consistency with the previous generator, it returns false for fields with
667// [default=""], preventing the generation of a default const or var for these
668// fields.
669//
670// TODO: Drop this special case.
671func fieldHasDefault(field *protogen.Field) bool {
672 if !field.Desc.HasDefault() {
673 return false
674 }
675 switch field.Desc.Kind() {
676 case protoreflect.StringKind:
677 return field.Desc.Default().String() != ""
678 case protoreflect.BytesKind:
679 return len(field.Desc.Default().Bytes()) > 0
680 }
681 return true
682}
683
Damien Neil658051b2018-09-10 12:26:21 -0700684func fieldJSONTag(field *protogen.Field) string {
685 return string(field.Desc.Name()) + ",omitempty"
686}
687
Damien Neild39efc82018-09-24 12:38:10 -0700688func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700689 // Special case for proto2 message sets: If this extension is extending
690 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
691 // then drop that last component.
692 //
693 // TODO: This should be implemented in the text formatter rather than the generator.
694 // In addition, the situation for when to apply this special case is implemented
695 // differently in other languages:
696 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
697 name := extension.Desc.FullName()
Damien Neil62386962018-10-30 10:35:48 -0700698 if n, ok := isExtensionMessageSetElement(extension); ok {
699 name = n
Damien Neil154da982018-09-19 13:21:58 -0700700 }
701
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800702 g.P("var ", extensionVar(f.File, extension), " = &", protoPackage.Ident("ExtensionDesc"), "{")
Damien Neil993c04d2018-09-14 15:41:11 -0700703 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
704 goType, pointer := fieldGoType(g, extension)
705 if pointer {
706 goType = "*" + goType
707 }
708 g.P("ExtensionType: (", goType, ")(nil),")
709 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700710 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700711 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
712 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
713 g.P("}")
714 g.P()
715}
716
Damien Neil62386962018-10-30 10:35:48 -0700717// isExtensionMessageSetELement returns the adjusted name of an extension
718// which extends proto2.bridge.MessageSet.
719func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800720 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700721 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
722 return "", false
723 }
724 if extension.ParentMessage == nil {
725 // This case shouldn't be given special handling at all--we're
726 // only supposed to drop the ".message_set_extension" for
727 // extensions defined within a message (i.e., the extension
728 // takes the message's name).
729 //
730 // This matches the behavior of the v1 generator, however.
731 //
732 // TODO: See if we can drop this case.
733 name = extension.Desc.FullName()
734 name = name[:len(name)-len("message_set_extension")]
735 return name, true
736 }
737 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700738}
739
Damien Neil993c04d2018-09-14 15:41:11 -0700740// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700741func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700742 name := "E_"
743 if extension.ParentMessage != nil {
744 name += extension.ParentMessage.GoIdent.GoName + "_"
745 }
746 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800747 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700748}
749
Damien Neilce36f8d2018-09-13 15:19:08 -0700750// genInitFunction generates an init function that registers the types in the
751// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700752func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Joe Tsaib6405bd2018-11-15 14:44:37 -0800753 if len(f.allEnums)+len(f.allMessages)+len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700754 return
755 }
756
757 g.P("func init() {")
Damien Neil154da982018-09-19 13:21:58 -0700758 for _, enum := range f.allEnums {
759 name := enum.GoIdent.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800760 g.P(protoPackage.Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700761 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700762 for _, message := range f.allMessages {
763 if message.Desc.IsMapEntry() {
764 continue
765 }
766
Damien Neil154da982018-09-19 13:21:58 -0700767 for _, extension := range message.Extensions {
768 genRegisterExtension(gen, g, f, extension)
769 }
770
Damien Neilce36f8d2018-09-13 15:19:08 -0700771 name := message.GoIdent.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800772 g.P(protoPackage.Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700773
774 // Types of map fields, sorted by the name of the field message type.
775 var mapFields []*protogen.Field
776 for _, field := range message.Fields {
777 if field.Desc.IsMap() {
778 mapFields = append(mapFields, field)
779 }
780 }
781 sort.Slice(mapFields, func(i, j int) bool {
782 ni := mapFields[i].MessageType.Desc.FullName()
783 nj := mapFields[j].MessageType.Desc.FullName()
784 return ni < nj
785 })
786 for _, field := range mapFields {
787 typeName := string(field.MessageType.Desc.FullName())
788 goType, _ := fieldGoType(g, field)
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800789 g.P(protoPackage.Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700790 }
791 }
Damien Neil154da982018-09-19 13:21:58 -0700792 for _, extension := range f.Extensions {
793 genRegisterExtension(gen, g, f, extension)
Damien Neil993c04d2018-09-14 15:41:11 -0700794 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700795 g.P("}")
796 g.P()
797}
798
Damien Neild39efc82018-09-24 12:38:10 -0700799func genRegisterExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800800 g.P(protoPackage.Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil154da982018-09-19 13:21:58 -0700801}
802
Damien Neil55fe1c02018-09-17 15:11:24 -0700803// deprecationComment returns a standard deprecation comment if deprecated is true.
804func deprecationComment(deprecated bool) string {
805 if !deprecated {
806 return ""
807 }
808 return "// Deprecated: Do not use."
809}
810
Damien Neilea7baf42018-09-28 14:23:44 -0700811func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700812 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700813 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700814 g.P()
815 }
816}
817
818// Names of messages and enums for which we will generate XXX_WellKnownType methods.
819var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700820 "google.protobuf.Any": true,
821 "google.protobuf.Duration": true,
822 "google.protobuf.Empty": true,
823 "google.protobuf.Struct": true,
824 "google.protobuf.Timestamp": true,
825
826 "google.protobuf.BoolValue": true,
827 "google.protobuf.BytesValue": true,
828 "google.protobuf.DoubleValue": true,
829 "google.protobuf.FloatValue": true,
830 "google.protobuf.Int32Value": true,
831 "google.protobuf.Int64Value": true,
832 "google.protobuf.ListValue": true,
833 "google.protobuf.NullValue": true,
834 "google.protobuf.StringValue": true,
835 "google.protobuf.UInt32Value": true,
836 "google.protobuf.UInt64Value": true,
837 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700838}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800839
840// genOneofField generates the struct field for a oneof.
841func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
842 if g.PrintLeadingComments(oneof.Location) {
843 g.P("//")
844 }
845 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
846 for _, field := range oneof.Fields {
847 g.PrintLeadingComments(field.Location)
848 g.P("//\t*", fieldOneofType(field))
849 }
850 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
851 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
852}
853
854// genOneofTypes generates the interface type used for a oneof field,
855// and the wrapper types that satisfy that interface.
856//
857// It also generates the getter method for the parent oneof field
858// (but not the member fields).
859func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
860 ifName := oneofInterfaceName(oneof)
861 g.P("type ", ifName, " interface {")
862 g.P(ifName, "()")
863 g.P("}")
864 g.P()
865 for _, field := range oneof.Fields {
866 name := fieldOneofType(field)
867 g.Annotate(name.GoName, field.Location)
868 g.Annotate(name.GoName+"."+field.GoName, field.Location)
869 g.P("type ", name, " struct {")
870 goType, _ := fieldGoType(g, field)
871 tags := []string{
872 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
873 }
874 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
875 g.P("}")
876 g.P()
877 }
878 for _, field := range oneof.Fields {
879 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
880 g.P()
881 }
882 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
883 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
884 g.P("if m != nil {")
885 g.P("return m.", oneofFieldName(oneof))
886 g.P("}")
887 g.P("return nil")
888 g.P("}")
889 g.P()
890}
891
892// oneofFieldName returns the name of the struct field holding the oneof value.
893//
894// This function is trivial, but pulling out the name like this makes it easier
895// to experiment with alternative oneof implementations.
896func oneofFieldName(oneof *protogen.Oneof) string {
897 return oneof.GoName
898}
899
900// oneofInterfaceName returns the name of the interface type implemented by
901// the oneof field value types.
902func oneofInterfaceName(oneof *protogen.Oneof) string {
903 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
904}
905
906// genOneofWrappers generates the XXX_OneofWrappers method for a message.
907func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
908 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
909 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
910 g.P("return []interface{}{")
911 for _, oneof := range message.Oneofs {
912 for _, field := range oneof.Fields {
913 g.P("(*", fieldOneofType(field), ")(nil),")
914 }
915 }
916 g.P("}")
917 g.P("}")
918 g.P()
919}
920
921// fieldOneofType returns the wrapper type used to represent a field in a oneof.
922func fieldOneofType(field *protogen.Field) protogen.GoIdent {
923 ident := protogen.GoIdent{
924 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
925 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
926 }
927 // Check for collisions with nested messages or enums.
928 //
929 // This conflict resolution is incomplete: Among other things, it
930 // does not consider collisions with other oneof field types.
931 //
932 // TODO: Consider dropping this entirely. Detecting conflicts and
933 // producing an error is almost certainly better than permuting
934 // field and type names in mostly unpredictable ways.
935Loop:
936 for {
937 for _, message := range field.ParentMessage.Messages {
938 if message.GoIdent == ident {
939 ident.GoName += "_"
940 continue Loop
941 }
942 }
943 for _, enum := range field.ParentMessage.Enums {
944 if enum.GoIdent == ident {
945 ident.GoName += "_"
946 continue Loop
947 }
948 }
949 return ident
950 }
951}