blob: cfa9e41a034ec82948da856e284392b006daf170 [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 "fmt"
Damien Neil7bf3ce22018-12-21 15:54:06 -080010 "go/ast"
11 "go/parser"
12 "go/token"
Damien Neilebc699d2018-09-13 08:50:13 -070013 "math"
Damien Neilce36f8d2018-09-13 15:19:08 -070014 "sort"
Damien Neil7779e052018-09-07 14:14:06 -070015 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070016 "strings"
Damien Neil7bf3ce22018-12-21 15:54:06 -080017 "unicode"
18 "unicode/utf8"
Damien Neil7779e052018-09-07 14:14:06 -070019
Joe Tsai05828db2018-11-01 13:52:16 -070020 "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsaica46d8c2019-03-20 16:51:09 -070021 "github.com/golang/protobuf/v2/internal/fieldnum"
Joe Tsaif31bf262019-03-18 14:54:34 -070022 "github.com/golang/protobuf/v2/proto"
Joe Tsai01ab2962018-09-21 17:44:00 -070023 "github.com/golang/protobuf/v2/protogen"
24 "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaie1f8d502018-11-26 18:55:29 -080025
26 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Damien Neil220c2022018-08-15 11:24:18 -070027)
28
Joe Tsaic1c17aa2018-11-16 11:14:14 -080029const (
Joe Tsai4fddeba2019-03-20 18:29:32 -070030 mathPackage = protogen.GoImportPath("math")
31 reflectPackage = protogen.GoImportPath("reflect")
32 protoPackage = protogen.GoImportPath("github.com/golang/protobuf/proto")
33 protoifacePackage = protogen.GoImportPath("github.com/golang/protobuf/v2/runtime/protoiface")
34 protoimplPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/runtime/protoimpl")
35 protoreflectPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/reflect/protoreflect")
36 protoregistryPackage = protogen.GoImportPath("github.com/golang/protobuf/v2/reflect/protoregistry")
37 prototypePackage = protogen.GoImportPath("github.com/golang/protobuf/v2/internal/prototype")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080038)
Damien Neil46abb572018-09-07 12:45:37 -070039
Damien Neild39efc82018-09-24 12:38:10 -070040type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070041 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080042
43 // vars containing the raw wire-encoded and compressed FileDescriptorProto.
44 descriptorRawVar string
45 descriptorGzipVar string
Joe Tsaib6405bd2018-11-15 14:44:37 -080046
Joe Tsai9667c482018-12-05 15:42:52 -080047 allEnums []*protogen.Enum
48 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
49 allMessages []*protogen.Message
50 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
51 allExtensions []*protogen.Extension
Damien Neilcab8dfe2018-09-06 14:51:28 -070052}
53
Damien Neil9c420a62018-09-27 15:26:33 -070054// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080055func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
56 filename := file.GeneratedFilenamePrefix + ".pb.go"
57 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -070058 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -070059 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -070060 }
61
Damien Neil8012b442019-01-18 09:32:24 -080062 // Collect all enums, messages, and extensions in "flattened ordering".
63 // See fileinit.FileBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -080064 f.allEnums = append(f.allEnums, f.Enums...)
65 f.allMessages = append(f.allMessages, f.Messages...)
66 f.allExtensions = append(f.allExtensions, f.Extensions...)
67 walkMessages(f.Messages, func(m *protogen.Message) {
68 f.allEnums = append(f.allEnums, m.Enums...)
69 f.allMessages = append(f.allMessages, m.Messages...)
70 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -070071 })
Damien Neilce36f8d2018-09-13 15:19:08 -070072
Joe Tsai9667c482018-12-05 15:42:52 -080073 // Derive a reverse mapping of enum and message pointers to their index
74 // in allEnums and allMessages.
75 if len(f.allEnums) > 0 {
76 f.allEnumsByPtr = make(map[*protogen.Enum]int)
77 for i, e := range f.allEnums {
78 f.allEnumsByPtr[e] = i
79 }
80 }
81 if len(f.allMessages) > 0 {
82 f.allMessagesByPtr = make(map[*protogen.Message]int)
83 for i, m := range f.allMessages {
84 f.allMessagesByPtr[m] = i
85 }
86 }
Joe Tsaib6405bd2018-11-15 14:44:37 -080087
Joe Tsai40692112019-02-27 20:25:51 -080088 // Determine the name of the var holding the file descriptor.
89 f.descriptorRawVar = "xxx_" + f.GoDescriptorIdent.GoName + "_rawdesc"
Damien Neil8012b442019-01-18 09:32:24 -080090 f.descriptorGzipVar = f.descriptorRawVar + "_gzipped"
Damien Neil46abb572018-09-07 12:45:37 -070091
Damien Neil220c2022018-08-15 11:24:18 -070092 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -070093 if f.Proto.GetOptions().GetDeprecated() {
94 g.P("// ", f.Desc.Path(), " is a deprecated file.")
95 } else {
96 g.P("// source: ", f.Desc.Path())
97 }
Damien Neil220c2022018-08-15 11:24:18 -070098 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -070099 g.PrintLeadingComments(protogen.Location{
100 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -0700101 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700102 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700103 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700104 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700105 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700106
Damien Neil73ac8852018-09-17 15:11:24 -0700107 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
108 genImport(gen, g, f, imps.Get(i))
109 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700110 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700111 genEnum(gen, g, f, enum)
112 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700113 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700114 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700115 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700116 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700117
Damien Neil7779e052018-09-07 14:14:06 -0700118 genFileDescriptor(gen, g, f)
Joe Tsaib6405bd2018-11-15 14:44:37 -0800119 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800120
121 return g
Damien Neil7779e052018-09-07 14:14:06 -0700122}
123
Damien Neil73ac8852018-09-17 15:11:24 -0700124// walkMessages calls f on each message and all of its descendants.
125func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
126 for _, m := range messages {
127 f(m)
128 walkMessages(m.Messages, f)
129 }
130}
131
Damien Neild39efc82018-09-24 12:38:10 -0700132func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700133 impFile, ok := gen.FileByName(imp.Path())
134 if !ok {
135 return
136 }
137 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700138 // Don't generate imports or aliases for types in the same Go package.
139 return
140 }
Damien Neil40a08052018-10-29 09:07:41 -0700141 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700142 // referenced, because other code and tools depend on having the
143 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700144 if !imp.IsWeak {
145 g.Import(impFile.GoImportPath)
146 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700147 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700148 return
149 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800150
151 // Generate public imports by generating the imported file, parsing it,
152 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800153 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800154 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800155 b, err := impGen.Content()
156 if err != nil {
157 gen.Error(err)
158 return
159 }
160 fset := token.NewFileSet()
161 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
162 if err != nil {
163 gen.Error(err)
164 return
165 }
Damien Neila7cbd062019-01-06 16:29:14 -0800166 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800167 // Don't import unexported symbols.
168 r, _ := utf8.DecodeRuneInString(name)
169 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700170 return
171 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800172 // Don't import the FileDescriptor.
173 if name == impFile.GoDescriptorIdent.GoName {
174 return
175 }
Damien Neila7cbd062019-01-06 16:29:14 -0800176 // Don't import decls referencing a symbol defined in another package.
177 // i.e., don't import decls which are themselves public imports:
178 //
179 // type T = somepackage.T
180 if _, ok := expr.(*ast.SelectorExpr); ok {
181 return
182 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800183 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
184 }
185 g.P("// Symbols defined in public import of ", imp.Path())
186 g.P()
187 for _, decl := range astFile.Decls {
188 switch decl := decl.(type) {
189 case *ast.GenDecl:
190 for _, spec := range decl.Specs {
191 switch spec := spec.(type) {
192 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800193 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800194 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800195 for i, name := range spec.Names {
196 var expr ast.Expr
197 if i < len(spec.Values) {
198 expr = spec.Values[i]
199 }
200 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800201 }
202 case *ast.ImportSpec:
203 default:
204 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800205 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700206 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700207 }
Damien Neil6b541312018-10-29 09:14:14 -0700208 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700209 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700210}
211
Damien Neild39efc82018-09-24 12:38:10 -0700212func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Joe Tsaif31bf262019-03-18 14:54:34 -0700213 // TODO: Replace this with v2 Clone.
214 descProto := new(descriptorpb.FileDescriptorProto)
215 b, err := proto.Marshal(f.Proto)
216 if err != nil {
217 gen.Error(err)
218 return
219 }
220 if err := proto.Unmarshal(b, descProto); err != nil {
221 gen.Error(err)
222 return
223 }
224
Damien Neil7779e052018-09-07 14:14:06 -0700225 // Trim the source_code_info from the descriptor.
Damien Neil7779e052018-09-07 14:14:06 -0700226 descProto.SourceCodeInfo = nil
Joe Tsaif31bf262019-03-18 14:54:34 -0700227 b, err = proto.MarshalOptions{Deterministic: true}.Marshal(descProto)
Damien Neil7779e052018-09-07 14:14:06 -0700228 if err != nil {
229 gen.Error(err)
230 return
231 }
Damien Neil7779e052018-09-07 14:14:06 -0700232
Damien Neil8012b442019-01-18 09:32:24 -0800233 g.P("var ", f.descriptorRawVar, " = []byte{")
234 g.P("// ", len(b), " bytes of the wire-encoded FileDescriptorProto")
Damien Neil7779e052018-09-07 14:14:06 -0700235 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 Neil8012b442019-01-18 09:32:24 -0800251
Joe Tsaicf81e672019-02-28 14:08:31 -0800252 // TODO: Modify CompressGZIP to lazy encode? Currently, the GZIP'd form
253 // is eagerly registered in v1, preventing any benefit from lazy encoding.
Joe Tsai8e506a82019-03-16 00:05:34 -0700254 g.P("var ", f.descriptorGzipVar, " = ", protoimplPackage.Ident("X"), ".CompressGZIP(", f.descriptorRawVar, ")")
Damien Neil8012b442019-01-18 09:32:24 -0800255 g.P()
Damien Neil220c2022018-08-15 11:24:18 -0700256}
Damien Neilc7d07d92018-08-22 13:46:02 -0700257
Damien Neild39efc82018-09-24 12:38:10 -0700258func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Damien Neilba1159f2018-10-17 12:53:18 -0700259 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700260 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700261 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800262 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700263 g.P("const (")
264 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700265 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700266 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700267 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800268 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700269 }
270 g.P(")")
271 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800272
273 // Generate support for protobuf reflection.
274 genReflectEnum(gen, g, f, enum)
275
Damien Neil46abb572018-09-07 12:45:37 -0700276 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsai8e506a82019-03-16 00:05:34 -0700277 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700278 g.P("var ", nameMap, " = map[int32]string{")
279 generated := make(map[protoreflect.EnumNumber]bool)
280 for _, value := range enum.Values {
281 duplicate := ""
282 if _, present := generated[value.Desc.Number()]; present {
283 duplicate = "// Duplicate value: "
284 }
285 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
286 generated[value.Desc.Number()] = true
287 }
288 g.P("}")
289 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700290
Damien Neil46abb572018-09-07 12:45:37 -0700291 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsai8e506a82019-03-16 00:05:34 -0700292 g.P("// Deprecated: Use ", enum.GoIdent.GoName, ".Type.Values instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700293 g.P("var ", valueMap, " = map[string]int32{")
294 for _, value := range enum.Values {
295 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
296 }
297 g.P("}")
298 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700299
Damien Neil46abb572018-09-07 12:45:37 -0700300 if enum.Desc.Syntax() != protoreflect.Proto3 {
301 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700302 g.P("return &x")
Damien Neil46abb572018-09-07 12:45:37 -0700303 g.P("}")
304 g.P()
305 }
306 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai8e506a82019-03-16 00:05:34 -0700307 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Type(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700308 g.P("}")
309 g.P()
310
Joe Tsai73903462018-12-14 12:22:41 -0800311 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700312 g.P("// Deprecated: Do not use.")
313 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
314 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Type(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700315 g.P("if err != nil {")
316 g.P("return err")
317 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700318 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700319 g.P("return nil")
320 g.P("}")
321 g.P()
322 }
323
324 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700325 for i := 1; i < len(enum.Location.Path); i += 2 {
326 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
Damien Neil46abb572018-09-07 12:45:37 -0700327 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700328 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
Damien Neil46abb572018-09-07 12:45:37 -0700329 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800330 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neil46abb572018-09-07 12:45:37 -0700331 g.P("}")
332 g.P()
333
Damien Neilea7baf42018-09-28 14:23:44 -0700334 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700335}
336
Damien Neil658051b2018-09-10 12:26:21 -0700337// enumRegistryName returns the name used to register an enum with the proto
338// package registry.
339//
340// Confusingly, this is <proto_package>.<go_ident>. This probably should have
341// been the full name of the proto enum type instead, but changing it at this
342// point would require thought.
343func enumRegistryName(enum *protogen.Enum) string {
344 // Find the FileDescriptor for this enum.
345 var desc protoreflect.Descriptor = enum.Desc
346 for {
347 p, ok := desc.Parent()
348 if !ok {
349 break
350 }
351 desc = p
352 }
353 fdesc := desc.(protoreflect.FileDescriptor)
Damien Neildaa4fad2018-10-08 14:08:27 -0700354 if fdesc.Package() == "" {
355 return enum.GoIdent.GoName
356 }
Damien Neil658051b2018-09-10 12:26:21 -0700357 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
358}
359
Damien Neild39efc82018-09-24 12:38:10 -0700360func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700361 if message.Desc.IsMapEntry() {
362 return
363 }
364
Damien Neilba1159f2018-10-17 12:53:18 -0700365 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800366 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700367 if hasComment {
368 g.P("//")
369 }
370 g.P(deprecationComment(true))
371 }
Damien Neil162c1272018-10-04 12:42:37 -0700372 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700373 g.P("type ", message.GoIdent, " struct {")
Damien Neil658051b2018-09-10 12:26:21 -0700374 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700375 if field.OneofType != nil {
376 // It would be a bit simpler to iterate over the oneofs below,
377 // but generating the field here keeps the contents of the Go
378 // struct in the same order as the contents of the source
379 // .proto file.
380 if field == field.OneofType.Fields[0] {
381 genOneofField(gen, g, f, message, field.OneofType)
382 }
Damien Neil658051b2018-09-10 12:26:21 -0700383 continue
384 }
Damien Neilba1159f2018-10-17 12:53:18 -0700385 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700386 goType, pointer := fieldGoType(g, field)
387 if pointer {
388 goType = "*" + goType
389 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700390 tags := []string{
391 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
392 fmt.Sprintf("json:%q", fieldJSONTag(field)),
393 }
394 if field.Desc.IsMap() {
395 key := field.MessageType.Fields[0]
396 val := field.MessageType.Fields[1]
397 tags = append(tags,
398 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
399 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
400 )
401 }
Damien Neil162c1272018-10-04 12:42:37 -0700402 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700403 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800404 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Damien Neil658051b2018-09-10 12:26:21 -0700405 }
406 g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`")
Damien Neil993c04d2018-09-14 15:41:11 -0700407
408 if message.Desc.ExtensionRanges().Len() > 0 {
409 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800410 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700411 tags = append(tags, `protobuf_messageset:"1"`)
412 }
413 tags = append(tags, `json:"-"`)
Joe Tsai4fddeba2019-03-20 18:29:32 -0700414 g.P("XXX_InternalExtensions ", protoimplPackage.Ident("ExtensionFieldsV1"), " `", strings.Join(tags, " "), "`")
Damien Neil993c04d2018-09-14 15:41:11 -0700415 }
Damien Neil658051b2018-09-10 12:26:21 -0700416 g.P("XXX_unrecognized []byte `json:\"-\"`")
417 g.P("XXX_sizecache int32 `json:\"-\"`")
Damien Neilc7d07d92018-08-22 13:46:02 -0700418 g.P("}")
419 g.P()
420
Joe Tsaib6405bd2018-11-15 14:44:37 -0800421 // Generate support for protobuf reflection.
422 genReflectMessage(gen, g, f, message)
423
Damien Neila1c6abc2018-09-12 13:36:34 -0700424 // Reset
425 g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }")
426 // String
Joe Tsai1321a0e2019-03-20 09:46:22 -0700427 if isDescriptor(f.File) {
428 g.P("func (m *", message.GoIdent, ") String() string { return ", protoimplPackage.Ident("X"), ".MessageStringOf(m) }")
429 } else {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700430 g.P("func (m *", message.GoIdent, ") String() string { return ", protoPackage.Ident("CompactTextString"), "(m) }")
Joe Tsai1321a0e2019-03-20 09:46:22 -0700431 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700432 // ProtoMessage
433 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
434 // Descriptor
435 var indexes []string
Damien Neil162c1272018-10-04 12:42:37 -0700436 for i := 1; i < len(message.Location.Path); i += 2 {
437 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
Damien Neila1c6abc2018-09-12 13:36:34 -0700438 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700439 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
Damien Neila1c6abc2018-09-12 13:36:34 -0700440 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
Damien Neil8012b442019-01-18 09:32:24 -0800441 g.P("return ", f.descriptorGzipVar, ", []int{", strings.Join(indexes, ","), "}")
Damien Neila1c6abc2018-09-12 13:36:34 -0700442 g.P("}")
Damien Neil993c04d2018-09-14 15:41:11 -0700443 g.P()
444
445 // ExtensionRangeArray
446 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700447 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700448 extRangeVar := "extRange_" + message.GoIdent.GoName
449 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
450 for i := 0; i < extranges.Len(); i++ {
451 r := extranges.Get(i)
452 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
453 }
454 g.P("}")
455 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700456 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700457 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
458 g.P("return ", extRangeVar)
459 g.P("}")
460 g.P()
461 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700462
Damien Neilea7baf42018-09-28 14:23:44 -0700463 genWellKnownType(g, "*", message.GoIdent, message.Desc)
464
Damien Neila1c6abc2018-09-12 13:36:34 -0700465 // Table-driven proto support.
466 //
467 // TODO: It does not scale to keep adding another method for every
468 // operation on protos that we want to switch over to using the
469 // table-driven approach. Instead, we should only add a single method
470 // that allows getting access to the *InternalMessageInfo struct and then
471 // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
Joe Tsai24ceb2b2018-12-04 22:53:56 -0800472 if !isDescriptor(f.File) {
473 // NOTE: We avoid adding table-driven support for descriptor proto
474 // since this depends on the v1 proto package, which would eventually
475 // need to depend on the descriptor itself.
476 messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName
477 // XXX_Unmarshal
478 g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {")
479 g.P("return ", messageInfoVar, ".Unmarshal(m, b)")
480 g.P("}")
481 // XXX_Marshal
482 g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
483 g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)")
484 g.P("}")
485 // XXX_Merge
486 g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {")
487 g.P(messageInfoVar, ".Merge(m, src)")
488 g.P("}")
489 // XXX_Size
490 g.P("func (m *", message.GoIdent, ") XXX_Size() int {")
491 g.P("return ", messageInfoVar, ".Size(m)")
492 g.P("}")
493 // XXX_DiscardUnknown
494 g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {")
495 g.P(messageInfoVar, ".DiscardUnknown(m)")
496 g.P("}")
497 g.P()
498 g.P("var ", messageInfoVar, " ", protoPackage.Ident("InternalMessageInfo"))
499 g.P()
500 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700501
Damien Neilebc699d2018-09-13 08:50:13 -0700502 // Constants and vars holding the default values of fields.
503 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800504 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700505 continue
506 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700507 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700508 def := field.Desc.Default()
509 switch field.Desc.Kind() {
510 case protoreflect.StringKind:
511 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
512 case protoreflect.BytesKind:
513 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
514 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700515 evalueDesc := field.Desc.DefaultEnumValue()
Damien Neilebc699d2018-09-13 08:50:13 -0700516 enum := field.EnumType
Damien Neila485fbd2018-10-26 13:28:37 -0700517 evalue := enum.Values[evalueDesc.Index()]
Damien Neilebc699d2018-09-13 08:50:13 -0700518 g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent)
519 case protoreflect.FloatKind, protoreflect.DoubleKind:
520 // Floating point numbers need extra handling for -Inf/Inf/NaN.
521 f := field.Desc.Default().Float()
522 goType := "float64"
523 if field.Desc.Kind() == protoreflect.FloatKind {
524 goType = "float32"
525 }
526 // funcCall returns a call to a function in the math package,
527 // possibly converting the result to float32.
528 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800529 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700530 if goType != "float64" {
531 s = goType + "(" + s + ")"
532 }
533 return s
534 }
535 switch {
536 case math.IsInf(f, -1):
537 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
538 case math.IsInf(f, 1):
539 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
540 case math.IsNaN(f):
541 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
542 default:
Damien Neil982684b2018-09-28 14:12:41 -0700543 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700544 }
545 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700546 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700547 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
548 }
549 }
550 g.P()
551
Damien Neil77f82fe2018-09-13 10:59:17 -0700552 // Getters.
553 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700554 if field.OneofType != nil {
555 if field == field.OneofType.Fields[0] {
556 genOneofTypes(gen, g, f, message, field.OneofType)
557 }
558 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700559 goType, pointer := fieldGoType(g, field)
560 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800561 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700562 g.P(deprecationComment(true))
563 }
Damien Neil162c1272018-10-04 12:42:37 -0700564 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Damien Neil1fa78d82018-09-13 13:12:36 -0700565 g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
566 if field.OneofType != nil {
Damien Neil81d6d832018-09-19 12:12:17 -0700567 g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700568 g.P("return x.", field.GoName)
569 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700570 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700571 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
572 g.P("if m != nil {")
573 } else {
574 g.P("if m != nil && m.", field.GoName, " != nil {")
575 }
576 star := ""
577 if pointer {
578 star = "*"
579 }
580 g.P("return ", star, " m.", field.GoName)
581 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700582 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700583 g.P("return ", defaultValue)
584 g.P("}")
585 g.P()
586 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700587
Damien Neil1fa78d82018-09-13 13:12:36 -0700588 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800589 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700590 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700591}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700592
Damien Neil77f82fe2018-09-13 10:59:17 -0700593// fieldGoType returns the Go type used for a field.
594//
595// If it returns pointer=true, the struct field is a pointer to the type.
596func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700597 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700598 switch field.Desc.Kind() {
599 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700600 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700601 case protoreflect.EnumKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700602 goType = g.QualifiedGoIdent(field.EnumType.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700603 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700604 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700605 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700606 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700607 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700608 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700609 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700610 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700611 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700612 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700613 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700615 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700616 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700617 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = "[]byte"
619 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700620 case protoreflect.MessageKind, protoreflect.GroupKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700621 if field.Desc.IsMap() {
622 keyType, _ := fieldGoType(g, field.MessageType.Fields[0])
623 valType, _ := fieldGoType(g, field.MessageType.Fields[1])
624 return fmt.Sprintf("map[%v]%v", keyType, valType), false
625 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700626 goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent)
627 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700628 }
629 if field.Desc.Cardinality() == protoreflect.Repeated {
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = "[]" + goType
631 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700632 }
Damien Neil44000a12018-10-24 12:31:16 -0700633 // Extension fields always have pointer type, even when defined in a proto3 file.
634 if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.ExtendedType() == nil {
Damien Neil77f82fe2018-09-13 10:59:17 -0700635 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700636 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700637 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700638}
639
640func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700641 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700642 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsai05828db2018-11-01 13:52:16 -0700643 enumName = enumRegistryName(field.EnumType)
Damien Neil658051b2018-09-10 12:26:21 -0700644 }
Joe Tsai05828db2018-11-01 13:52:16 -0700645 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700646}
647
Damien Neil77f82fe2018-09-13 10:59:17 -0700648func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
649 if field.Desc.Cardinality() == protoreflect.Repeated {
650 return "nil"
651 }
Joe Tsai9667c482018-12-05 15:42:52 -0800652 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700653 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700654 if field.Desc.Kind() == protoreflect.BytesKind {
655 return "append([]byte(nil), " + defVarName + "...)"
656 }
657 return defVarName
658 }
659 switch field.Desc.Kind() {
660 case protoreflect.BoolKind:
661 return "false"
662 case protoreflect.StringKind:
663 return `""`
664 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
665 return "nil"
666 case protoreflect.EnumKind:
667 return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent)
668 default:
669 return "0"
670 }
671}
672
Damien Neil658051b2018-09-10 12:26:21 -0700673func fieldJSONTag(field *protogen.Field) string {
674 return string(field.Desc.Name()) + ",omitempty"
675}
676
Joe Tsaiafb455e2019-03-14 16:08:22 -0700677func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
678 if len(f.allExtensions) == 0 {
679 return
Damien Neil154da982018-09-19 13:21:58 -0700680 }
681
Joe Tsai4fddeba2019-03-20 18:29:32 -0700682 g.P("var ", extDecsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700683 for _, extension := range f.allExtensions {
684 // Special case for proto2 message sets: If this extension is extending
685 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
686 // then drop that last component.
687 //
688 // TODO: This should be implemented in the text formatter rather than the generator.
689 // In addition, the situation for when to apply this special case is implemented
690 // differently in other languages:
691 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
692 name := extension.Desc.FullName()
693 if n, ok := isExtensionMessageSetElement(extension); ok {
694 name = n
695 }
696
697 g.P("{")
698 g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),")
699 goType, pointer := fieldGoType(g, extension)
700 if pointer {
701 goType = "*" + goType
702 }
703 g.P("ExtensionType: (", goType, ")(nil),")
704 g.P("Field: ", extension.Desc.Number(), ",")
705 g.P("Name: ", strconv.Quote(string(name)), ",")
706 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
707 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
708 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700709 }
Damien Neil993c04d2018-09-14 15:41:11 -0700710 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700711
712 g.P("var (")
713 for i, extension := range f.allExtensions {
714 ed := extension.Desc
715 targetName := string(ed.ExtendedType().FullName())
716 typeName := ed.Kind().String()
717 switch ed.Kind() {
718 case protoreflect.EnumKind:
719 typeName = string(ed.EnumType().FullName())
720 case protoreflect.MessageKind, protoreflect.GroupKind:
721 typeName = string(ed.MessageType().FullName())
722 }
723 fieldName := string(ed.Name())
724 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
725 g.P(extensionVar(f.File, extension), " = &", extDecsVarName(f), "[", i, "]")
726 g.P()
727 }
728 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700729}
730
Damien Neil62386962018-10-30 10:35:48 -0700731// isExtensionMessageSetELement returns the adjusted name of an extension
732// which extends proto2.bridge.MessageSet.
733func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800734 opts := extension.ExtendedType.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700735 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
736 return "", false
737 }
738 if extension.ParentMessage == nil {
739 // This case shouldn't be given special handling at all--we're
740 // only supposed to drop the ".message_set_extension" for
741 // extensions defined within a message (i.e., the extension
742 // takes the message's name).
743 //
744 // This matches the behavior of the v1 generator, however.
745 //
746 // TODO: See if we can drop this case.
747 name = extension.Desc.FullName()
748 name = name[:len(name)-len("message_set_extension")]
749 return name, true
750 }
751 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700752}
753
Damien Neil993c04d2018-09-14 15:41:11 -0700754// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700755func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700756 name := "E_"
757 if extension.ParentMessage != nil {
758 name += extension.ParentMessage.GoIdent.GoName + "_"
759 }
760 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800761 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700762}
763
Joe Tsai559d47f2019-03-19 18:21:47 -0700764// genRegistrationV1 generates the init function body that registers the
765// types in the generated file with the v1 proto package.
766func genRegistrationV1(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
Joe Tsai08cd8842019-03-18 13:46:39 -0700767 // TODO: Remove this function when we always register with v2.
768 if isDescriptor(f.File) {
769 return
770 }
771
Joe Tsai8e506a82019-03-16 00:05:34 -0700772 g.P(protoPackage.Ident("RegisterFile"), "(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorGzipVar, ")")
Damien Neil154da982018-09-19 13:21:58 -0700773 for _, enum := range f.allEnums {
774 name := enum.GoIdent.GoName
Joe Tsai8e506a82019-03-16 00:05:34 -0700775 g.P(protoPackage.Ident("RegisterEnum"), fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name))
Damien Neil154da982018-09-19 13:21:58 -0700776 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700777 for _, message := range f.allMessages {
778 if message.Desc.IsMapEntry() {
779 continue
780 }
781
782 name := message.GoIdent.GoName
Joe Tsai8e506a82019-03-16 00:05:34 -0700783 g.P(protoPackage.Ident("RegisterType"), fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName()))
Damien Neilce36f8d2018-09-13 15:19:08 -0700784
785 // Types of map fields, sorted by the name of the field message type.
786 var mapFields []*protogen.Field
787 for _, field := range message.Fields {
788 if field.Desc.IsMap() {
789 mapFields = append(mapFields, field)
790 }
791 }
792 sort.Slice(mapFields, func(i, j int) bool {
793 ni := mapFields[i].MessageType.Desc.FullName()
794 nj := mapFields[j].MessageType.Desc.FullName()
795 return ni < nj
796 })
797 for _, field := range mapFields {
798 typeName := string(field.MessageType.Desc.FullName())
799 goType, _ := fieldGoType(g, field)
Joe Tsai8e506a82019-03-16 00:05:34 -0700800 g.P(protoPackage.Ident("RegisterMapType"), fmt.Sprintf("((%v)(nil), %q)", goType, typeName))
Damien Neilce36f8d2018-09-13 15:19:08 -0700801 }
802 }
Joe Tsai9667c482018-12-05 15:42:52 -0800803 for _, extension := range f.allExtensions {
Joe Tsai8e506a82019-03-16 00:05:34 -0700804 g.P(protoPackage.Ident("RegisterExtension"), "(", extensionVar(f.File, extension), ")")
Damien Neil993c04d2018-09-14 15:41:11 -0700805 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700806}
807
Damien Neil55fe1c02018-09-17 15:11:24 -0700808// deprecationComment returns a standard deprecation comment if deprecated is true.
809func deprecationComment(deprecated bool) string {
810 if !deprecated {
811 return ""
812 }
813 return "// Deprecated: Do not use."
814}
815
Damien Neilea7baf42018-09-28 14:23:44 -0700816func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700817 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700818 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700819 g.P()
820 }
821}
822
823// Names of messages and enums for which we will generate XXX_WellKnownType methods.
824var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700825 "google.protobuf.Any": true,
826 "google.protobuf.Duration": true,
827 "google.protobuf.Empty": true,
828 "google.protobuf.Struct": true,
829 "google.protobuf.Timestamp": true,
830
831 "google.protobuf.BoolValue": true,
832 "google.protobuf.BytesValue": true,
833 "google.protobuf.DoubleValue": true,
834 "google.protobuf.FloatValue": true,
835 "google.protobuf.Int32Value": true,
836 "google.protobuf.Int64Value": true,
837 "google.protobuf.ListValue": true,
838 "google.protobuf.NullValue": true,
839 "google.protobuf.StringValue": true,
840 "google.protobuf.UInt32Value": true,
841 "google.protobuf.UInt64Value": true,
842 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700843}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800844
845// genOneofField generates the struct field for a oneof.
846func genOneofField(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
847 if g.PrintLeadingComments(oneof.Location) {
848 g.P("//")
849 }
850 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
851 for _, field := range oneof.Fields {
852 g.PrintLeadingComments(field.Location)
853 g.P("//\t*", fieldOneofType(field))
854 }
855 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
856 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
857}
858
859// genOneofTypes generates the interface type used for a oneof field,
860// and the wrapper types that satisfy that interface.
861//
862// It also generates the getter method for the parent oneof field
863// (but not the member fields).
864func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
865 ifName := oneofInterfaceName(oneof)
866 g.P("type ", ifName, " interface {")
867 g.P(ifName, "()")
868 g.P("}")
869 g.P()
870 for _, field := range oneof.Fields {
871 name := fieldOneofType(field)
872 g.Annotate(name.GoName, field.Location)
873 g.Annotate(name.GoName+"."+field.GoName, field.Location)
874 g.P("type ", name, " struct {")
875 goType, _ := fieldGoType(g, field)
876 tags := []string{
877 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
878 }
879 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
880 g.P("}")
881 g.P()
882 }
883 for _, field := range oneof.Fields {
884 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
885 g.P()
886 }
887 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
888 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", ifName, " {")
889 g.P("if m != nil {")
890 g.P("return m.", oneofFieldName(oneof))
891 g.P("}")
892 g.P("return nil")
893 g.P("}")
894 g.P()
895}
896
897// oneofFieldName returns the name of the struct field holding the oneof value.
898//
899// This function is trivial, but pulling out the name like this makes it easier
900// to experiment with alternative oneof implementations.
901func oneofFieldName(oneof *protogen.Oneof) string {
902 return oneof.GoName
903}
904
905// oneofInterfaceName returns the name of the interface type implemented by
906// the oneof field value types.
907func oneofInterfaceName(oneof *protogen.Oneof) string {
908 return fmt.Sprintf("is%s_%s", oneof.ParentMessage.GoIdent.GoName, oneof.GoName)
909}
910
911// genOneofWrappers generates the XXX_OneofWrappers method for a message.
912func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
913 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
914 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
915 g.P("return []interface{}{")
916 for _, oneof := range message.Oneofs {
917 for _, field := range oneof.Fields {
918 g.P("(*", fieldOneofType(field), ")(nil),")
919 }
920 }
921 g.P("}")
922 g.P("}")
923 g.P()
924}
925
926// fieldOneofType returns the wrapper type used to represent a field in a oneof.
927func fieldOneofType(field *protogen.Field) protogen.GoIdent {
928 ident := protogen.GoIdent{
929 GoImportPath: field.ParentMessage.GoIdent.GoImportPath,
930 GoName: field.ParentMessage.GoIdent.GoName + "_" + field.GoName,
931 }
932 // Check for collisions with nested messages or enums.
933 //
934 // This conflict resolution is incomplete: Among other things, it
935 // does not consider collisions with other oneof field types.
936 //
937 // TODO: Consider dropping this entirely. Detecting conflicts and
938 // producing an error is almost certainly better than permuting
939 // field and type names in mostly unpredictable ways.
940Loop:
941 for {
942 for _, message := range field.ParentMessage.Messages {
943 if message.GoIdent == ident {
944 ident.GoName += "_"
945 continue Loop
946 }
947 }
948 for _, enum := range field.ParentMessage.Enums {
949 if enum.GoIdent == ident {
950 ident.GoName += "_"
951 continue Loop
952 }
953 }
954 return ident
955 }
956}