blob: c3154f5355f7f1c0d46eeb5cca53c5947890c549 [file] [log] [blame]
Damien Neil220c2022018-08-15 11:24:18 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Damien Neil1adaec92018-09-24 13:43:03 -07005// Package internal_gengo is internal to the protobuf module.
6package internal_gengo
Damien Neil220c2022018-08-15 11:24:18 -07007
8import (
Damien Neil7779e052018-09-07 14:14:06 -07009 "bytes"
10 "compress/gzip"
11 "crypto/sha256"
12 "encoding/hex"
13 "fmt"
Damien Neilebc699d2018-09-13 08:50:13 -070014 "math"
Damien Neilce36f8d2018-09-13 15:19:08 -070015 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070016 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070017 "strings"
Damien Neil7779e052018-09-07 14:14:06 -070018
19 "github.com/golang/protobuf/proto"
20 descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
Joe Tsai01ab2962018-09-21 17:44:00 -070021 "github.com/golang/protobuf/v2/protogen"
22 "github.com/golang/protobuf/v2/reflect/protoreflect"
Damien Neil220c2022018-08-15 11:24:18 -070023)
24
Damien Neild4127922018-09-12 11:13:49 -070025// generatedCodeVersion indicates a version of the generated code.
26// It is incremented whenever an incompatibility between the generated code and
27// proto package is introduced; the generated code references
28// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
29const generatedCodeVersion = 2
30
Damien Neil46abb572018-09-07 12:45:37 -070031const protoPackage = "github.com/golang/protobuf/proto"
32
Damien Neild39efc82018-09-24 12:38:10 -070033type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070034 *protogen.File
Damien Neil46abb572018-09-07 12:45:37 -070035 locationMap map[string][]*descpb.SourceCodeInfo_Location
36 descriptorVar string // var containing the gzipped FileDescriptorProto
Damien Neilce36f8d2018-09-13 15:19:08 -070037 allEnums []*protogen.Enum
38 allMessages []*protogen.Message
Damien Neil993c04d2018-09-14 15:41:11 -070039 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070040}
41
Damien Neil9c420a62018-09-27 15:26:33 -070042// GenerateFile generates the contents of a .pb.go file.
43func GenerateFile(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
Damien Neild39efc82018-09-24 12:38:10 -070044 f := &fileInfo{
Damien Neilcab8dfe2018-09-06 14:51:28 -070045 File: file,
46 locationMap: make(map[string][]*descpb.SourceCodeInfo_Location),
47 }
48 for _, loc := range file.Proto.GetSourceCodeInfo().GetLocation() {
49 key := pathKey(loc.Path)
50 f.locationMap[key] = append(f.locationMap[key], loc)
51 }
52
Damien Neil993c04d2018-09-14 15:41:11 -070053 // The different order for enums and extensions is to match the output
54 // of the previous implementation.
55 //
56 // TODO: Eventually make this consistent.
Damien Neilce36f8d2018-09-13 15:19:08 -070057 f.allEnums = append(f.allEnums, f.File.Enums...)
Damien Neil73ac8852018-09-17 15:11:24 -070058 walkMessages(f.Messages, func(message *protogen.Message) {
59 f.allMessages = append(f.allMessages, message)
60 f.allEnums = append(f.allEnums, message.Enums...)
61 f.allExtensions = append(f.allExtensions, message.Extensions...)
62 })
Damien Neil993c04d2018-09-14 15:41:11 -070063 f.allExtensions = append(f.allExtensions, f.File.Extensions...)
Damien Neilce36f8d2018-09-13 15:19:08 -070064
Damien Neil46abb572018-09-07 12:45:37 -070065 // Determine the name of the var holding the file descriptor:
66 //
67 // fileDescriptor_<hash of filename>
68 filenameHash := sha256.Sum256([]byte(f.Desc.Path()))
69 f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8]))
70
Damien Neil220c2022018-08-15 11:24:18 -070071 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070072 if f.Proto.GetOptions().GetDeprecated() {
73 g.P("// ", f.Desc.Path(), " is a deprecated file.")
74 } else {
75 g.P("// source: ", f.Desc.Path())
76 }
Damien Neil220c2022018-08-15 11:24:18 -070077 g.P()
Damien Neilcab8dfe2018-09-06 14:51:28 -070078 const filePackageField = 2 // FileDescriptorProto.package
Damien Neil162c1272018-10-04 12:42:37 -070079 genComment(g, f, protogen.Location{Path: []int32{filePackageField}})
Damien Neilcab8dfe2018-09-06 14:51:28 -070080 g.P()
Damien Neil082ce922018-09-06 10:23:53 -070081 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -070082 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -070083
84 // These references are not necessary, since we automatically add
85 // all necessary imports before formatting the generated file.
86 //
87 // This section exists to generate output more consistent with
88 // the previous version of protoc-gen-go, to make it easier to
89 // detect unintended variations.
90 //
91 // TODO: Eventually remove this.
92 g.P("// Reference imports to suppress errors if they are not otherwise used.")
93 g.P("var _ = ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "Marshal"})
94 g.P("var _ = ", protogen.GoIdent{GoImportPath: "fmt", GoName: "Errorf"})
95 g.P("var _ = ", protogen.GoIdent{GoImportPath: "math", GoName: "Inf"})
96 g.P()
97
Damien Neild4127922018-09-12 11:13:49 -070098 g.P("// This is a compile-time assertion to ensure that this generated file")
99 g.P("// is compatible with the proto package it is being compiled against.")
100 g.P("// A compilation error at this line likely means your copy of the")
101 g.P("// proto package needs to be updated.")
102 g.P("const _ = ", protogen.GoIdent{
103 GoImportPath: protoPackage,
104 GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion),
105 }, "// please upgrade the proto package")
106 g.P()
Damien Neilc7d07d92018-08-22 13:46:02 -0700107
Damien Neil73ac8852018-09-17 15:11:24 -0700108 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
109 genImport(gen, g, f, imps.Get(i))
110 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700111 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700112 genEnum(gen, g, f, enum)
113 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700114 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700115 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700116 }
Damien Neil993c04d2018-09-14 15:41:11 -0700117 for _, extension := range f.Extensions {
118 genExtension(gen, g, f, extension)
119 }
Damien Neil220c2022018-08-15 11:24:18 -0700120
Damien Neilce36f8d2018-09-13 15:19:08 -0700121 genInitFunction(gen, g, f)
Damien Neil7779e052018-09-07 14:14:06 -0700122 genFileDescriptor(gen, g, f)
123}
124
Damien Neil73ac8852018-09-17 15:11:24 -0700125// walkMessages calls f on each message and all of its descendants.
126func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
127 for _, m := range messages {
128 f(m)
129 walkMessages(m.Messages, f)
130 }
131}
132
Damien Neild39efc82018-09-24 12:38:10 -0700133func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700134 impFile, ok := gen.FileByName(imp.Path())
135 if !ok {
136 return
137 }
138 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700139 // Don't generate imports or aliases for types in the same Go package.
140 return
141 }
142 // Generate imports for all dependencies, even if they are not
143 // referenced, because other code and tools depend on having the
144 // full transitive closure of protocol buffer types in the binary.
145 g.Import(impFile.GoImportPath)
146 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700147 return
148 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700149 // TODO: An alternate approach to generating public imports might be
150 // to generate the imported file contents, parse it, and extract all
151 // exported identifiers from the AST to build a list of forwarding
152 // declarations.
153 //
154 // TODO: Consider whether this should generate recursive aliases. e.g.,
155 // if a.proto publicly imports b.proto publicly imports c.proto, should
156 // a.pb.go contain aliases for symbols defined in c.proto?
Damien Neil73ac8852018-09-17 15:11:24 -0700157 var enums []*protogen.Enum
158 enums = append(enums, impFile.Enums...)
159 walkMessages(impFile.Messages, func(message *protogen.Message) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700160 if message.Desc.IsMapEntry() {
161 return
162 }
Damien Neil73ac8852018-09-17 15:11:24 -0700163 enums = append(enums, message.Enums...)
Damien Neil2193e8d2018-10-09 12:49:13 -0700164 for _, field := range message.Fields {
165 if !fieldHasDefault(field) {
166 continue
167 }
168 defVar := protogen.GoIdent{
169 GoImportPath: message.GoIdent.GoImportPath,
170 GoName: "Default_" + message.GoIdent.GoName + "_" + field.GoName,
171 }
172 decl := "const"
173 if field.Desc.Kind() == protoreflect.BytesKind {
174 decl = "var"
175 }
176 g.P(decl, " ", defVar.GoName, " = ", defVar)
177 }
Damien Neil73ac8852018-09-17 15:11:24 -0700178 g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path())
179 g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent)
180 for _, oneof := range message.Oneofs {
181 for _, field := range oneof.Fields {
182 typ := fieldOneofType(field)
183 g.P("type ", typ.GoName, " = ", typ)
184 }
185 }
186 g.P()
187 })
188 for _, enum := range enums {
189 g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path())
190 g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent)
191 g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name")
192 g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value")
193 g.P()
194 for _, value := range enum.Values {
195 g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")")
196 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700197 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700198 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700199}
200
Damien Neild39efc82018-09-24 12:38:10 -0700201func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil7779e052018-09-07 14:14:06 -0700202 // Trim the source_code_info from the descriptor.
203 // Marshal and gzip it.
204 descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto)
205 descProto.SourceCodeInfo = nil
206 b, err := proto.Marshal(descProto)
207 if err != nil {
208 gen.Error(err)
209 return
210 }
211 var buf bytes.Buffer
212 w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
213 w.Write(b)
214 w.Close()
215 b = buf.Bytes()
216
Damien Neil46abb572018-09-07 12:45:37 -0700217 g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }")
Damien Neil7779e052018-09-07 14:14:06 -0700218 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700219 g.P("var ", f.descriptorVar, " = []byte{")
Damien Neil7779e052018-09-07 14:14:06 -0700220 g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
221 for len(b) > 0 {
222 n := 16
223 if n > len(b) {
224 n = len(b)
225 }
226
227 s := ""
228 for _, c := range b[:n] {
229 s += fmt.Sprintf("0x%02x,", c)
230 }
231 g.P(s)
232
233 b = b[n:]
234 }
235 g.P("}")
236 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700237}
Damien Neilc7d07d92018-08-22 13:46:02 -0700238
Damien Neild39efc82018-09-24 12:38:10 -0700239func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neil162c1272018-10-04 12:42:37 -0700240 genComment(g, f, enum.Location)
241 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700242 g.P("type ", enum.GoIdent, " int32",
243 deprecationComment(enumOptions(gen, enum).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700244 g.P("const (")
245 for _, value := range enum.Values {
Damien Neil162c1272018-10-04 12:42:37 -0700246 genComment(g, f, value.Location)
247 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700248 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
249 deprecationComment(enumValueOptions(gen, value).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700250 }
251 g.P(")")
252 g.P()
253 nameMap := enum.GoIdent.GoName + "_name"
254 g.P("var ", nameMap, " = map[int32]string{")
255 generated := make(map[protoreflect.EnumNumber]bool)
256 for _, value := range enum.Values {
257 duplicate := ""
258 if _, present := generated[value.Desc.Number()]; present {
259 duplicate = "// Duplicate value: "
260 }
261 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
262 generated[value.Desc.Number()] = true
263 }
264 g.P("}")
265 g.P()
266 valueMap := enum.GoIdent.GoName + "_value"
267 g.P("var ", valueMap, " = map[string]int32{")
268 for _, value := range enum.Values {
269 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
270 }
271 g.P("}")
272 g.P()
273 if enum.Desc.Syntax() != protoreflect.Proto3 {
274 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
275 g.P("p := new(", enum.GoIdent, ")")
276 g.P("*p = x")
277 g.P("return p")
278 g.P("}")
279 g.P()
280 }
281 g.P("func (x ", enum.GoIdent, ") String() string {")
282 g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))")
283 g.P("}")
284 g.P()
285
286 if enum.Desc.Syntax() != protoreflect.Proto3 {
287 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {")
288 g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`)
289 g.P("if err != nil {")
290 g.P("return err")
291 g.P("}")
292 g.P("*x = ", enum.GoIdent, "(value)")
293 g.P("return nil")
294 g.P("}")
295 g.P()
296 }
297
298 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700299 for i := 1; i < len(enum.Location.Path); i += 2 {
300 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700301 }
302 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
303 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
304 g.P("}")
305 g.P()
306
Damien Neilea7baf42018-09-28 14:23:44 -0700307 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700308}
309
Damien Neil658051b2018-09-10 12:26:21 -0700310// enumRegistryName returns the name used to register an enum with the proto
311// package registry.
312//
313// Confusingly, this is <proto_package>.<go_ident>. This probably should have
314// been the full name of the proto enum type instead, but changing it at this
315// point would require thought.
316func enumRegistryName(enum *protogen.Enum) string {
317 // Find the FileDescriptor for this enum.
318 var desc protoreflect.Descriptor = enum.Desc
319 for {
320 p, ok := desc.Parent()
321 if !ok {
322 break
323 }
324 desc = p
325 }
326 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700327 if fdesc.Package() == "" {
328 return enum.GoIdent.GoName
329 }
Damien Neil658051b2018-09-10 12:26:21 -0700330 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
331}
332
Damien Neild39efc82018-09-24 12:38:10 -0700333func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700334 if message.Desc.IsMapEntry() {
335 return
336 }
337
Damien Neil162c1272018-10-04 12:42:37 -0700338 hasComment := genComment(g, f, message.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700339 if messageOptions(gen, message).GetDeprecated() {
340 if hasComment {
341 g.P("//")
342 }
343 g.P(deprecationComment(true))
344 }
Damien Neil162c1272018-10-04 12:42:37 -0700345 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700346 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700347 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700348 if field.OneofType != nil {
349 // It would be a bit simpler to iterate over the oneofs below,
350 // but generating the field here keeps the contents of the Go
351 // struct in the same order as the contents of the source
352 // .proto file.
353 if field == field.OneofType.Fields[0] {
354 genOneofField(gen, g, f, message, field.OneofType)
355 }
Damien Neil658051b2018-09-10 12:26:21 -0700356 continue
357 }
Damien Neil162c1272018-10-04 12:42:37 -0700358 genComment(g, f, field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700359 goType, pointer := fieldGoType(g, field)
360 if pointer {
361 goType = "*" + goType
362 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700363 tags := []string{
364 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
365 fmt.Sprintf("json:%q", fieldJSONTag(field)),
366 }
367 if field.Desc.IsMap() {
368 key := field.MessageType.Fields[0]
369 val := field.MessageType.Fields[1]
370 tags = append(tags,
371 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
372 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
373 )
374 }
Damien Neil162c1272018-10-04 12:42:37 -0700375 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700376 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
377 deprecationComment(fieldOptions(gen, field).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700378 }
379 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700380
381 if message.Desc.ExtensionRanges().Len() > 0 {
382 var tags []string
383 if messageOptions(gen, message).GetMessageSetWireFormat() {
384 tags = append(tags, `protobuf_messageset:"1"`)
385 }
386 tags = append(tags, `json:"-"`)
387 g.P(protogen.GoIdent{
388 GoImportPath: protoPackage,
389 GoName: "XXX_InternalExtensions",
390 }, " `", strings.Join(tags, " "), "`")
391 }
Damien Neil658051b2018-09-10 12:26:21 -0700392 // TODO XXX_InternalExtensions
393 g.P("XXX_unrecognized []byte `json:\"-\"`")
394 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700395 g.P("}")
396 g.P()
397
Damien Neila1c6abc2018-09-12 13:36:34 -0700398 // Reset
399 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
400 // String
401 g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{
402 GoImportPath: protoPackage,
403 GoName: "CompactTextString",
404 }, "(m) }")
405 // ProtoMessage
406 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
407 // Descriptor
408 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700409 for i := 1; i < len(message.Location.Path); i += 2 {
410 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700411 }
412 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
413 g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}")
414 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700415 g.P()
416
417 // ExtensionRangeArray
418 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
419 if messageOptions(gen, message).GetMessageSetWireFormat() {
420 g.P("func (m *", message.GoIdent, ") MarshalJSON() ([]byte, error) {")
421 g.P("return ", protogen.GoIdent{
422 GoImportPath: protoPackage,
423 GoName: "MarshalMessageSetJSON",
424 }, "(&m.XXX_InternalExtensions)")
425 g.P("}")
426 g.P("func (m *", message.GoIdent, ") UnmarshalJSON(buf []byte) error {")
427 g.P("return ", protogen.GoIdent{
428 GoImportPath: protoPackage,
429 GoName: "UnmarshalMessageSetJSON",
430 }, "(buf, &m.XXX_InternalExtensions)")
431 g.P("}")
432 g.P()
433 }
434
435 protoExtRange := protogen.GoIdent{
436 GoImportPath: protoPackage,
437 GoName: "ExtensionRange",
438 }
439 extRangeVar := "extRange_" + message.GoIdent.GoName
440 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
441 for i := 0; i < extranges.Len(); i++ {
442 r := extranges.Get(i)
443 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
444 }
445 g.P("}")
446 g.P()
447 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
448 g.P("return ", extRangeVar)
449 g.P("}")
450 g.P()
451 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700452
Damien Neilea7baf42018-09-28 14:23:44 -0700453 genWellKnownType(g, "*", message.GoIdent, message.Desc)
454
Damien Neila1c6abc2018-09-12 13:36:34 -0700455 // Table-driven proto support.
456 //
457 // TODO: It does not scale to keep adding another method for every
458 // operation on protos that we want to switch over to using the
459 // table-driven approach. Instead, we should only add a single method
460 // that allows getting access to the *InternalMessageInfo struct and then
461 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
462 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
463 // XXX_Unmarshal
464 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
465 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
466 g.P("}")
467 // XXX_Marshal
468 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
469 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
470 g.P("}")
471 // XXX_Merge
472 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
473 g.P(messageInfoVar, ".Merge(m, src)")
474 g.P("}")
475 // XXX_Size
476 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
477 g.P("return ", messageInfoVar, ".Size(m)")
478 g.P("}")
479 // XXX_DiscardUnknown
480 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
481 g.P(messageInfoVar, ".DiscardUnknown(m)")
482 g.P("}")
483 g.P()
484 g.P("var ", messageInfoVar, " ", protogen.GoIdent{
485 GoImportPath: protoPackage,
486 GoName: "InternalMessageInfo",
487 })
488 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:
503 enum := field.EnumType
504 evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()]
505 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
506 case protoreflect.FloatKind, protoreflect.DoubleKind:
507 // Floating point numbers need extra handling for -Inf/Inf/NaN.
508 f := field.Desc.Default().Float()
509 goType := "float64"
510 if field.Desc.Kind() == protoreflect.FloatKind {
511 goType = "float32"
512 }
513 // funcCall returns a call to a function in the math package,
514 // possibly converting the result to float32.
515 funcCall := func(fn, param string) string {
516 s := g.QualifiedGoIdent(protogen.GoIdent{
517 GoImportPath: "math",
518 GoName: fn,
519 }) + param
520 if goType != "float64" {
521 s = goType + "(" + s + ")"
522 }
523 return s
524 }
525 switch {
526 case math.IsInf(f, -1):
527 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
528 case math.IsInf(f, 1):
529 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
530 case math.IsNaN(f):
531 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
532 default:
Damien Neil982684b2018-09-28 14:12:41 -0700533 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700534 }
535 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700536 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700537 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
538 }
539 }
540 g.P()
541
Damien Neil77f82fe2018-09-13 10:59:17 -0700542 // Getters.
543 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700544 if field.OneofType != nil {
545 if field == field.OneofType.Fields[0] {
546 genOneofTypes(gen, g, f, message, field.OneofType)
547 }
548 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700549 goType, pointer := fieldGoType(g, field)
550 defaultValue := fieldDefaultValue(g, message, field)
Damien Neil55fe1c02018-09-17 15:11:24 -0700551 if fieldOptions(gen, field).GetDeprecated() {
552 g.P(deprecationComment(true))
553 }
Damien Neil162c1272018-10-04 12:42:37 -0700554 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700555 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
556 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700557 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700558 g.P("return x.", field.GoName)
559 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700560 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700561 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
562 g.P("if m != nil {")
563 } else {
564 g.P("if m != nil && m.", field.GoName, " != nil {")
565 }
566 star := ""
567 if pointer {
568 star = "*"
569 }
570 g.P("return ", star, " m.", field.GoName)
571 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700572 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700573 g.P("return ", defaultValue)
574 g.P("}")
575 g.P()
576 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700577
Damien Neil1fa78d82018-09-13 13:12:36 -0700578 if len(message.Oneofs) > 0 {
579 genOneofFuncs(gen, g, f, message)
580 }
Damien Neil993c04d2018-09-14 15:41:11 -0700581 for _, extension := range message.Extensions {
582 genExtension(gen, g, f, extension)
583 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700584}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700585
Damien Neil77f82fe2018-09-13 10:59:17 -0700586// fieldGoType returns the Go type used for a field.
587//
588// If it returns pointer=true, the struct field is a pointer to the type.
589func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700590 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700591 switch field.Desc.Kind() {
592 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700593 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700594 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700595 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700596 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700597 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700598 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700599 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700600 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700601 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700602 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700603 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700604 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700605 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700606 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700607 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700608 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700609 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700610 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700611 goType = "[]byte"
612 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700613 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700614 if field.Desc.IsMap() {
615 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
616 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
617 return fmt.Sprintf("map[%v]%v", keyType, valType), false
618 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700619 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
620 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700621 }
622 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700623 goType = "[]" + goType
624 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700625 }
626 if field.Desc.Syntax() == protoreflect.Proto3 {
Damien Neil77f82fe2018-09-13 10:59:17 -0700627 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700628 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700629 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700630}
631
632func fieldProtobufTag(field *protogen.Field) string {
633 var tag []string
634 // wire type
635 tag = append(tag, wireTypes[field.Desc.Kind()])
636 // field number
637 tag = append(tag, strconv.Itoa(int(field.Desc.Number())))
638 // cardinality
639 switch field.Desc.Cardinality() {
640 case protoreflect.Optional:
641 tag = append(tag, "opt")
642 case protoreflect.Required:
643 tag = append(tag, "req")
644 case protoreflect.Repeated:
645 tag = append(tag, "rep")
646 }
Damien Neild4803f52018-09-19 11:43:35 -0700647 if field.Desc.IsPacked() {
648 tag = append(tag, "packed")
649 }
Damien Neil658051b2018-09-10 12:26:21 -0700650 // TODO: packed
651 // name
652 name := string(field.Desc.Name())
653 if field.Desc.Kind() == protoreflect.GroupKind {
654 // The name of the FieldDescriptor for a group field is
655 // lowercased. To find the original capitalization, we
656 // look in the field's MessageType.
657 name = string(field.MessageType.Desc.Name())
658 }
659 tag = append(tag, "name="+name)
660 // JSON name
661 if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name {
662 tag = append(tag, "json="+jsonName)
663 }
664 // proto3
665 if field.Desc.Syntax() == protoreflect.Proto3 {
666 tag = append(tag, "proto3")
667 }
668 // enum
669 if field.Desc.Kind() == protoreflect.EnumKind {
670 tag = append(tag, "enum="+enumRegistryName(field.EnumType))
671 }
672 // oneof
673 if field.Desc.OneofType() != nil {
674 tag = append(tag, "oneof")
675 }
Damien Neilebc699d2018-09-13 08:50:13 -0700676 // default value
677 // This must appear last in the tag, since commas in strings aren't escaped.
678 if field.Desc.HasDefault() {
679 var def string
680 switch field.Desc.Kind() {
681 case protoreflect.BoolKind:
682 if field.Desc.Default().Bool() {
683 def = "1"
684 } else {
685 def = "0"
686 }
687 case protoreflect.BytesKind:
688 def = string(field.Desc.Default().Bytes())
689 case protoreflect.FloatKind, protoreflect.DoubleKind:
690 f := field.Desc.Default().Float()
691 switch {
692 case math.IsInf(f, -1):
693 def = "-inf"
694 case math.IsInf(f, 1):
695 def = "inf"
696 case math.IsNaN(f):
697 def = "nan"
698 default:
Damien Neil982684b2018-09-28 14:12:41 -0700699 def = fmt.Sprint(field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700700 }
701 default:
702 def = fmt.Sprint(field.Desc.Default().Interface())
703 }
704 tag = append(tag, "def="+def)
705 }
Damien Neil658051b2018-09-10 12:26:21 -0700706 return strings.Join(tag, ",")
707}
708
Damien Neil77f82fe2018-09-13 10:59:17 -0700709func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
710 if field.Desc.Cardinality() == protoreflect.Repeated {
711 return "nil"
712 }
Damien Neilccf3fa62018-09-28 14:41:45 -0700713 if fieldHasDefault(field) {
Damien Neil1fa78d82018-09-13 13:12:36 -0700714 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700715 if field.Desc.Kind() == protoreflect.BytesKind {
716 return "append([]byte(nil), " + defVarName + "...)"
717 }
718 return defVarName
719 }
720 switch field.Desc.Kind() {
721 case protoreflect.BoolKind:
722 return "false"
723 case protoreflect.StringKind:
724 return `""`
725 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
726 return "nil"
727 case protoreflect.EnumKind:
728 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
729 default:
730 return "0"
731 }
732}
733
Damien Neilccf3fa62018-09-28 14:41:45 -0700734// fieldHasDefault returns true if we consider a field to have a default value.
735//
736// For consistency with the previous generator, it returns false for fields with
737// [default=""], preventing the generation of a default const or var for these
738// fields.
739//
740// TODO: Drop this special case.
741func fieldHasDefault(field *protogen.Field) bool {
742 if !field.Desc.HasDefault() {
743 return false
744 }
745 switch field.Desc.Kind() {
746 case protoreflect.StringKind:
747 return field.Desc.Default().String() != ""
748 case protoreflect.BytesKind:
749 return len(field.Desc.Default().Bytes()) > 0
750 }
751 return true
752}
753
Damien Neil658051b2018-09-10 12:26:21 -0700754var wireTypes = map[protoreflect.Kind]string{
755 protoreflect.BoolKind: "varint",
756 protoreflect.EnumKind: "varint",
757 protoreflect.Int32Kind: "varint",
758 protoreflect.Sint32Kind: "zigzag32",
759 protoreflect.Uint32Kind: "varint",
760 protoreflect.Int64Kind: "varint",
761 protoreflect.Sint64Kind: "zigzag64",
762 protoreflect.Uint64Kind: "varint",
763 protoreflect.Sfixed32Kind: "fixed32",
764 protoreflect.Fixed32Kind: "fixed32",
765 protoreflect.FloatKind: "fixed32",
766 protoreflect.Sfixed64Kind: "fixed64",
767 protoreflect.Fixed64Kind: "fixed64",
768 protoreflect.DoubleKind: "fixed64",
769 protoreflect.StringKind: "bytes",
770 protoreflect.BytesKind: "bytes",
771 protoreflect.MessageKind: "bytes",
772 protoreflect.GroupKind: "group",
773}
774
775func fieldJSONTag(field *protogen.Field) string {
776 return string(field.Desc.Name()) + ",omitempty"
777}
778
Damien Neild39efc82018-09-24 12:38:10 -0700779func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700780 // Special case for proto2 message sets: If this extension is extending
781 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
782 // then drop that last component.
783 //
784 // TODO: This should be implemented in the text formatter rather than the generator.
785 // In addition, the situation for when to apply this special case is implemented
786 // differently in other languages:
787 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
788 name := extension.Desc.FullName()
789 if isExtensionMessageSetElement(gen, extension) {
790 name = name.Parent()
791 }
792
Damien Neil993c04d2018-09-14 15:41:11 -0700793 g.P("var ", extensionVar(f, extension), " = &", protogen.GoIdent{
794 GoImportPath: protoPackage,
795 GoName: "ExtensionDesc",
796 }, "{")
797 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
798 goType, pointer := fieldGoType(g, extension)
799 if pointer {
800 goType = "*" + goType
801 }
802 g.P("ExtensionType: (", goType, ")(nil),")
803 g.P("Field: ", extension.Desc.Number(), ",")
Damien Neil154da982018-09-19 13:21:58 -0700804 g.P("Name: ", strconv.Quote(string(name)), ",")
Damien Neil993c04d2018-09-14 15:41:11 -0700805 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
806 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
807 g.P("}")
808 g.P()
809}
810
Damien Neil154da982018-09-19 13:21:58 -0700811func isExtensionMessageSetElement(gen *protogen.Plugin, extension *protogen.Extension) bool {
812 return extension.ParentMessage != nil &&
813 messageOptions(gen, extension.ExtendedType).GetMessageSetWireFormat() &&
814 extension.Desc.Name() == "message_set_extension"
815}
816
Damien Neil993c04d2018-09-14 15:41:11 -0700817// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neild39efc82018-09-24 12:38:10 -0700818func extensionVar(f *fileInfo, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700819 name := "E_"
820 if extension.ParentMessage != nil {
821 name += extension.ParentMessage.GoIdent.GoName + "_"
822 }
823 name += extension.GoName
824 return protogen.GoIdent{
825 GoImportPath: f.GoImportPath,
826 GoName: name,
827 }
828}
829
Damien Neilce36f8d2018-09-13 15:19:08 -0700830// genInitFunction generates an init function that registers the types in the
831// generated file with the proto package.
Damien Neild39efc82018-09-24 12:38:10 -0700832func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Damien Neil993c04d2018-09-14 15:41:11 -0700833 if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 {
Damien Neilce36f8d2018-09-13 15:19:08 -0700834 return
835 }
836
837 g.P("func init() {")
Damien Neil154da982018-09-19 13:21:58 -0700838 for _, enum := range f.allEnums {
839 name := enum.GoIdent.GoName
840 g.P(protogen.GoIdent{
841 GoImportPath: protoPackage,
842 GoName: "RegisterEnum",
843 }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
844 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700845 for _, message := range f.allMessages {
846 if message.Desc.IsMapEntry() {
847 continue
848 }
849
Damien Neil154da982018-09-19 13:21:58 -0700850 for _, extension := range message.Extensions {
851 genRegisterExtension(gen, g, f, extension)
852 }
853
Damien Neilce36f8d2018-09-13 15:19:08 -0700854 name := message.GoIdent.GoName
855 g.P(protogen.GoIdent{
856 GoImportPath: protoPackage,
857 GoName: "RegisterType",
858 }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
859
860 // Types of map fields, sorted by the name of the field message type.
861 var mapFields []*protogen.Field
862 for _, field := range message.Fields {
863 if field.Desc.IsMap() {
864 mapFields = append(mapFields, field)
865 }
866 }
867 sort.Slice(mapFields, func(i, j int) bool {
868 ni := mapFields[i].MessageType.Desc.FullName()
869 nj := mapFields[j].MessageType.Desc.FullName()
870 return ni < nj
871 })
872 for _, field := range mapFields {
873 typeName := string(field.MessageType.Desc.FullName())
874 goType, _ := fieldGoType(g, field)
875 g.P(protogen.GoIdent{
876 GoImportPath: protoPackage,
877 GoName: "RegisterMapType",
878 }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
879 }
880 }
Damien Neil154da982018-09-19 13:21:58 -0700881 for _, extension := range f.Extensions {
882 genRegisterExtension(gen, g, f, extension)
Damien Neil993c04d2018-09-14 15:41:11 -0700883 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700884 g.P("}")
885 g.P()
886}
887
Damien Neild39efc82018-09-24 12:38:10 -0700888func genRegisterExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, extension *protogen.Extension) {
Damien Neil154da982018-09-19 13:21:58 -0700889 g.P(protogen.GoIdent{
890 GoImportPath: protoPackage,
891 GoName: "RegisterExtension",
892 }, "(", extensionVar(f, extension), ")")
893 if isExtensionMessageSetElement(gen, extension) {
894 goType, pointer := fieldGoType(g, extension)
895 if pointer {
896 goType = "*" + goType
897 }
898 g.P(protogen.GoIdent{
899 GoImportPath: protoPackage,
900 GoName: "RegisterMessageSetType",
901 }, "((", goType, ")(nil), ", extension.Desc.Number(), ",", strconv.Quote(string(extension.Desc.FullName().Parent())), ")")
902 }
903}
904
Damien Neil162c1272018-10-04 12:42:37 -0700905func genComment(g *protogen.GeneratedFile, f *fileInfo, loc protogen.Location) (hasComment bool) {
906 for _, loc := range f.locationMap[pathKey(loc.Path)] {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700907 if loc.LeadingComments == nil {
908 continue
909 }
910 for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
Damien Neil1fa78d82018-09-13 13:12:36 -0700911 hasComment = true
Damien Neilcab8dfe2018-09-06 14:51:28 -0700912 g.P("//", line)
913 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700914 break
Damien Neilcab8dfe2018-09-06 14:51:28 -0700915 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700916 return hasComment
Damien Neilcab8dfe2018-09-06 14:51:28 -0700917}
918
Damien Neil55fe1c02018-09-17 15:11:24 -0700919// deprecationComment returns a standard deprecation comment if deprecated is true.
920func deprecationComment(deprecated bool) string {
921 if !deprecated {
922 return ""
923 }
924 return "// Deprecated: Do not use."
925}
926
Damien Neilcab8dfe2018-09-06 14:51:28 -0700927// pathKey converts a location path to a string suitable for use as a map key.
928func pathKey(path []int32) string {
929 var buf []byte
930 for i, x := range path {
931 if i != 0 {
932 buf = append(buf, ',')
933 }
934 buf = strconv.AppendInt(buf, int64(x), 10)
935 }
936 return string(buf)
937}
Damien Neil46abb572018-09-07 12:45:37 -0700938
Damien Neilea7baf42018-09-28 14:23:44 -0700939func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700940 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700941 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700942 g.P()
943 }
944}
945
946// Names of messages and enums for which we will generate XXX_WellKnownType methods.
947var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700948 "google.protobuf.Any": true,
949 "google.protobuf.Duration": true,
950 "google.protobuf.Empty": true,
951 "google.protobuf.Struct": true,
952 "google.protobuf.Timestamp": true,
953
954 "google.protobuf.BoolValue": true,
955 "google.protobuf.BytesValue": true,
956 "google.protobuf.DoubleValue": true,
957 "google.protobuf.FloatValue": true,
958 "google.protobuf.Int32Value": true,
959 "google.protobuf.Int64Value": true,
960 "google.protobuf.ListValue": true,
961 "google.protobuf.NullValue": true,
962 "google.protobuf.StringValue": true,
963 "google.protobuf.UInt32Value": true,
964 "google.protobuf.UInt64Value": true,
965 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700966}