blob: 22d87ca407b12f194d0cdb0c3a0c50a0e6249d01 [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 Neil7779e052018-09-07 14:14:06 -070014 "strconv"
Damien Neilcab8dfe2018-09-06 14:51:28 -070015 "strings"
Damien Neil7bf3ce22018-12-21 15:54:06 -080016 "unicode"
17 "unicode/utf8"
Damien Neil7779e052018-09-07 14:14:06 -070018
Damien Neil5c5b5312019-05-14 12:44:37 -070019 "google.golang.org/protobuf/compiler/protogen"
Damien Neile89e6242019-05-13 23:55:40 -070020 "google.golang.org/protobuf/internal/encoding/tag"
21 "google.golang.org/protobuf/internal/fieldnum"
Damien Neile89e6242019-05-13 23:55:40 -070022 "google.golang.org/protobuf/reflect/protoreflect"
Joe Tsai58b42d82019-05-22 16:27:51 -040023 "google.golang.org/protobuf/runtime/protoimpl"
Joe Tsaie1f8d502018-11-26 18:55:29 -080024
Joe Tsaia95b29f2019-05-16 12:47:20 -070025 "google.golang.org/protobuf/types/descriptorpb"
Damien Neil220c2022018-08-15 11:24:18 -070026)
27
Joe Tsaic1c17aa2018-11-16 11:14:14 -080028const (
Joe Tsaiab61d412019-04-16 15:23:29 -070029 // generateEnumMapVars specifies whether to generate enum maps,
30 // which provide a bi-directional mapping between enum numbers and names.
31 generateEnumMapVars = true
32
33 // generateRawDescMethods specifies whether to generate EnumDescriptor and
34 // Descriptor methods for enums and messages. These methods return the
35 // GZIP'd contents of the raw file descriptor and the path from the root
36 // to the given enum or message descriptor.
37 generateRawDescMethods = true
Joe Tsai09912272019-07-08 10:38:11 -070038
39 // generateOneofWrapperMethods specifies whether to generate
40 // XXX_OneofWrappers methods on messages with oneofs.
41 generateOneofWrapperMethods = false
Joe Tsaic0e4bb22019-07-06 13:05:11 -070042
43 // generateNoUnkeyedLiteralFields specifies whether to generate
44 // the XXX_NoUnkeyedLiteral field.
45 generateNoUnkeyedLiteralFields = false
46
47 // generateExportedSizeCacheFields specifies whether to generate an exported
48 // XXX_sizecache field instead of an unexported sizeCache field.
49 generateExportedSizeCacheFields = false
50
51 // generateExportedUnknownFields specifies whether to generate an exported
52 // XXX_unrecognized field instead of an unexported unknownFields field.
53 generateExportedUnknownFields = false
54
55 // generateExportedExtensionFields specifies whether to generate an exported
56 // XXX_InternalExtensions field instead of an unexported extensionFields field.
57 generateExportedExtensionFields = false
Joe Tsaiab61d412019-04-16 15:23:29 -070058)
59
60const (
Joe Tsai5d72cc22019-03-28 01:13:26 -070061 syncPackage = protogen.GoImportPath("sync")
Joe Tsai4fddeba2019-03-20 18:29:32 -070062 mathPackage = protogen.GoImportPath("math")
Damien Neile89e6242019-05-13 23:55:40 -070063 protoifacePackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoiface")
64 protoimplPackage = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoimpl")
65 protoreflectPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoreflect")
66 protoregistryPackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoregistry")
Joe Tsaid8881392019-06-06 13:01:53 -070067 prototypePackage = protogen.GoImportPath("google.golang.org/protobuf/reflect/prototype")
Joe Tsaic1c17aa2018-11-16 11:14:14 -080068)
Damien Neil46abb572018-09-07 12:45:37 -070069
Damien Neild39efc82018-09-24 12:38:10 -070070type fileInfo struct {
Damien Neilcab8dfe2018-09-06 14:51:28 -070071 *protogen.File
Damien Neil8012b442019-01-18 09:32:24 -080072
Joe Tsaic0e4bb22019-07-06 13:05:11 -070073 allEnums []*protogen.Enum
74 allMessages []*protogen.Message
75 allExtensions []*protogen.Extension
76
77 allEnumsByPtr map[*protogen.Enum]int // value is index into allEnums
78 allMessagesByPtr map[*protogen.Message]int // value is index into allMessages
79 allMessageFieldsByPtr map[*protogen.Message]*structFields
80}
81
82type structFields struct {
83 count int
84 unexported map[int]string
85}
86
87func (sf *structFields) append(name string) {
88 if r, _ := utf8.DecodeRuneInString(name); !unicode.IsUpper(r) {
89 if sf.unexported == nil {
90 sf.unexported = make(map[int]string)
91 }
92 sf.unexported[sf.count] = name
93 }
94 sf.count++
Damien Neilcab8dfe2018-09-06 14:51:28 -070095}
96
Damien Neil9c420a62018-09-27 15:26:33 -070097// GenerateFile generates the contents of a .pb.go file.
Joe Tsai19058432019-02-27 21:46:29 -080098func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
99 filename := file.GeneratedFilenamePrefix + ".pb.go"
100 g := gen.NewGeneratedFile(filename, file.GoImportPath)
Damien Neild39efc82018-09-24 12:38:10 -0700101 f := &fileInfo{
Damien Neilba1159f2018-10-17 12:53:18 -0700102 File: file,
Damien Neilcab8dfe2018-09-06 14:51:28 -0700103 }
104
Damien Neil8012b442019-01-18 09:32:24 -0800105 // Collect all enums, messages, and extensions in "flattened ordering".
Joe Tsaid8881392019-06-06 13:01:53 -0700106 // See filetype.TypeBuilder.
Joe Tsai9667c482018-12-05 15:42:52 -0800107 f.allEnums = append(f.allEnums, f.Enums...)
108 f.allMessages = append(f.allMessages, f.Messages...)
109 f.allExtensions = append(f.allExtensions, f.Extensions...)
110 walkMessages(f.Messages, func(m *protogen.Message) {
111 f.allEnums = append(f.allEnums, m.Enums...)
112 f.allMessages = append(f.allMessages, m.Messages...)
113 f.allExtensions = append(f.allExtensions, m.Extensions...)
Damien Neil73ac8852018-09-17 15:11:24 -0700114 })
Damien Neilce36f8d2018-09-13 15:19:08 -0700115
Joe Tsai9667c482018-12-05 15:42:52 -0800116 // Derive a reverse mapping of enum and message pointers to their index
117 // in allEnums and allMessages.
118 if len(f.allEnums) > 0 {
119 f.allEnumsByPtr = make(map[*protogen.Enum]int)
120 for i, e := range f.allEnums {
121 f.allEnumsByPtr[e] = i
122 }
123 }
124 if len(f.allMessages) > 0 {
125 f.allMessagesByPtr = make(map[*protogen.Message]int)
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700126 f.allMessageFieldsByPtr = make(map[*protogen.Message]*structFields)
Joe Tsai9667c482018-12-05 15:42:52 -0800127 for i, m := range f.allMessages {
128 f.allMessagesByPtr[m] = i
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700129 f.allMessageFieldsByPtr[m] = new(structFields)
Joe Tsai9667c482018-12-05 15:42:52 -0800130 }
131 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800132
Damien Neil220c2022018-08-15 11:24:18 -0700133 g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
Damien Neil55fe1c02018-09-17 15:11:24 -0700134 if f.Proto.GetOptions().GetDeprecated() {
135 g.P("// ", f.Desc.Path(), " is a deprecated file.")
136 } else {
137 g.P("// source: ", f.Desc.Path())
138 }
Damien Neil220c2022018-08-15 11:24:18 -0700139 g.P()
Damien Neilba1159f2018-10-17 12:53:18 -0700140 g.PrintLeadingComments(protogen.Location{
141 SourceFile: f.Proto.GetName(),
Joe Tsaica46d8c2019-03-20 16:51:09 -0700142 Path: []int32{fieldnum.FileDescriptorProto_Package},
Damien Neilba1159f2018-10-17 12:53:18 -0700143 })
Damien Neilcab8dfe2018-09-06 14:51:28 -0700144 g.P()
Damien Neil082ce922018-09-06 10:23:53 -0700145 g.P("package ", f.GoPackageName)
Damien Neilc7d07d92018-08-22 13:46:02 -0700146 g.P()
Damien Neil1ec33152018-09-13 13:12:36 -0700147
Joe Tsai5d72cc22019-03-28 01:13:26 -0700148 // Emit a static check that enforces a minimum version of the proto package.
Joe Tsai58b42d82019-05-22 16:27:51 -0400149 g.P("const (")
150 g.P("// Verify that runtime/protoimpl is sufficiently up-to-date.")
151 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("MaxVersion"), " - ", protoimpl.Version, ")")
152 g.P("// Verify that this generated code is sufficiently up-to-date.")
153 g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimpl.Version, " - ", protoimplPackage.Ident("MinVersion"), ")")
154 g.P(")")
Joe Tsai5d72cc22019-03-28 01:13:26 -0700155 g.P()
156
Damien Neil73ac8852018-09-17 15:11:24 -0700157 for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ {
158 genImport(gen, g, f, imps.Get(i))
159 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700160 for _, enum := range f.allEnums {
Damien Neil46abb572018-09-07 12:45:37 -0700161 genEnum(gen, g, f, enum)
162 }
Damien Neilce36f8d2018-09-13 15:19:08 -0700163 for _, message := range f.allMessages {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700164 genMessage(gen, g, f, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700165 }
Joe Tsaiafb455e2019-03-14 16:08:22 -0700166 genExtensions(gen, g, f)
Damien Neil220c2022018-08-15 11:24:18 -0700167
Joe Tsaib6405bd2018-11-15 14:44:37 -0800168 genReflectFileDescriptor(gen, g, f)
Joe Tsai19058432019-02-27 21:46:29 -0800169
170 return g
Damien Neil7779e052018-09-07 14:14:06 -0700171}
172
Damien Neil73ac8852018-09-17 15:11:24 -0700173// walkMessages calls f on each message and all of its descendants.
174func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) {
175 for _, m := range messages {
176 f(m)
177 walkMessages(m.Messages, f)
178 }
179}
180
Damien Neild39efc82018-09-24 12:38:10 -0700181func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) {
Damien Neil73ac8852018-09-17 15:11:24 -0700182 impFile, ok := gen.FileByName(imp.Path())
183 if !ok {
184 return
185 }
186 if impFile.GoImportPath == f.GoImportPath {
Damien Neil2e0c3da2018-09-19 12:51:36 -0700187 // Don't generate imports or aliases for types in the same Go package.
188 return
189 }
Damien Neil40a08052018-10-29 09:07:41 -0700190 // Generate imports for all non-weak dependencies, even if they are not
Damien Neil2e0c3da2018-09-19 12:51:36 -0700191 // referenced, because other code and tools depend on having the
192 // full transitive closure of protocol buffer types in the binary.
Damien Neil40a08052018-10-29 09:07:41 -0700193 if !imp.IsWeak {
194 g.Import(impFile.GoImportPath)
195 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700196 if !imp.IsPublic {
Damien Neil73ac8852018-09-17 15:11:24 -0700197 return
198 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800199
200 // Generate public imports by generating the imported file, parsing it,
201 // and extracting every symbol that should receive a forwarding declaration.
Joe Tsai19058432019-02-27 21:46:29 -0800202 impGen := GenerateFile(gen, impFile)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800203 impGen.Skip()
Damien Neil7bf3ce22018-12-21 15:54:06 -0800204 b, err := impGen.Content()
205 if err != nil {
206 gen.Error(err)
207 return
208 }
209 fset := token.NewFileSet()
210 astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments)
211 if err != nil {
212 gen.Error(err)
213 return
214 }
Damien Neila7cbd062019-01-06 16:29:14 -0800215 genForward := func(tok token.Token, name string, expr ast.Expr) {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800216 // Don't import unexported symbols.
217 r, _ := utf8.DecodeRuneInString(name)
218 if !unicode.IsUpper(r) {
Damien Neil2193e8d2018-10-09 12:49:13 -0700219 return
220 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800221 // Don't import the FileDescriptor.
222 if name == impFile.GoDescriptorIdent.GoName {
223 return
224 }
Damien Neila7cbd062019-01-06 16:29:14 -0800225 // Don't import decls referencing a symbol defined in another package.
226 // i.e., don't import decls which are themselves public imports:
227 //
228 // type T = somepackage.T
229 if _, ok := expr.(*ast.SelectorExpr); ok {
230 return
231 }
Damien Neil7bf3ce22018-12-21 15:54:06 -0800232 g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name))
233 }
234 g.P("// Symbols defined in public import of ", imp.Path())
235 g.P()
236 for _, decl := range astFile.Decls {
237 switch decl := decl.(type) {
238 case *ast.GenDecl:
239 for _, spec := range decl.Specs {
240 switch spec := spec.(type) {
241 case *ast.TypeSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800242 genForward(decl.Tok, spec.Name.Name, spec.Type)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800243 case *ast.ValueSpec:
Damien Neila7cbd062019-01-06 16:29:14 -0800244 for i, name := range spec.Names {
245 var expr ast.Expr
246 if i < len(spec.Values) {
247 expr = spec.Values[i]
248 }
249 genForward(decl.Tok, name.Name, expr)
Damien Neil7bf3ce22018-12-21 15:54:06 -0800250 }
251 case *ast.ImportSpec:
252 default:
253 panic(fmt.Sprintf("can't generate forward for spec type %T", spec))
Damien Neil7e5c6472018-11-29 08:57:07 -0800254 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700255 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700256 }
Damien Neil6b541312018-10-29 09:14:14 -0700257 }
Damien Neil2193e8d2018-10-09 12:49:13 -0700258 g.P()
Damien Neilce36f8d2018-09-13 15:19:08 -0700259}
260
Damien Neild39efc82018-09-24 12:38:10 -0700261func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, enum *protogen.Enum) {
Joe Tsai61968ce2019-04-01 12:59:24 -0700262 // Enum type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700263 g.PrintLeadingComments(enum.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700264 g.Annotate(enum.GoIdent.GoName, enum.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700265 g.P("type ", enum.GoIdent, " int32",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800266 deprecationComment(enum.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()))
Joe Tsai61968ce2019-04-01 12:59:24 -0700267
268 // Enum value constants.
Damien Neil46abb572018-09-07 12:45:37 -0700269 g.P("const (")
270 for _, value := range enum.Values {
Damien Neilba1159f2018-10-17 12:53:18 -0700271 g.PrintLeadingComments(value.Location)
Damien Neil162c1272018-10-04 12:42:37 -0700272 g.Annotate(value.GoIdent.GoName, value.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700273 g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number(),
Joe Tsaie1f8d502018-11-26 18:55:29 -0800274 deprecationComment(value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()))
Damien Neil46abb572018-09-07 12:45:37 -0700275 }
276 g.P(")")
277 g.P()
Joe Tsaib6405bd2018-11-15 14:44:37 -0800278
Joe Tsai61968ce2019-04-01 12:59:24 -0700279 // Enum value mapping (number -> name).
Joe Tsaiab61d412019-04-16 15:23:29 -0700280 if generateEnumMapVars {
281 nameMap := enum.GoIdent.GoName + "_name"
Joe Tsaiab61d412019-04-16 15:23:29 -0700282 g.P("var ", nameMap, " = map[int32]string{")
283 generated := make(map[protoreflect.EnumNumber]bool)
284 for _, value := range enum.Values {
285 duplicate := ""
286 if _, present := generated[value.Desc.Number()]; present {
287 duplicate = "// Duplicate value: "
288 }
289 g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",")
290 generated[value.Desc.Number()] = true
Damien Neil46abb572018-09-07 12:45:37 -0700291 }
Joe Tsaiab61d412019-04-16 15:23:29 -0700292 g.P("}")
293 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700294 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700295
Joe Tsai61968ce2019-04-01 12:59:24 -0700296 // Enum value mapping (name -> number).
Joe Tsaiab61d412019-04-16 15:23:29 -0700297 if generateEnumMapVars {
298 valueMap := enum.GoIdent.GoName + "_value"
Joe Tsaiab61d412019-04-16 15:23:29 -0700299 g.P("var ", valueMap, " = map[string]int32{")
300 for _, value := range enum.Values {
301 g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",")
302 }
303 g.P("}")
304 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700305 }
Joe Tsai8e506a82019-03-16 00:05:34 -0700306
Joe Tsai61968ce2019-04-01 12:59:24 -0700307 // Enum method.
Joe Tsaidbab6c02019-05-14 15:06:03 -0700308 //
309 // NOTE: A pointer value is needed to represent presence in proto2.
310 // Since a proto2 message can reference a proto3 enum, it is useful to
311 // always generate this method (even on proto3 enums) to support that case.
312 g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {")
313 g.P("p := new(", enum.GoIdent, ")")
314 g.P("*p = x")
315 g.P("return p")
316 g.P("}")
317 g.P()
318
Joe Tsai61968ce2019-04-01 12:59:24 -0700319 // String method.
Damien Neil46abb572018-09-07 12:45:37 -0700320 g.P("func (x ", enum.GoIdent, ") String() string {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700321 g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))")
Damien Neil46abb572018-09-07 12:45:37 -0700322 g.P("}")
323 g.P()
324
Joe Tsai61968ce2019-04-01 12:59:24 -0700325 genReflectEnum(gen, g, f, enum)
326
327 // UnmarshalJSON method.
Joe Tsai73903462018-12-14 12:22:41 -0800328 if enum.Desc.Syntax() == protoreflect.Proto2 {
Joe Tsai8e506a82019-03-16 00:05:34 -0700329 g.P("// Deprecated: Do not use.")
330 g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(b []byte) error {")
Joe Tsai0fc49f82019-05-01 12:29:25 -0700331 g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)")
Damien Neil46abb572018-09-07 12:45:37 -0700332 g.P("if err != nil {")
333 g.P("return err")
334 g.P("}")
Joe Tsai8e506a82019-03-16 00:05:34 -0700335 g.P("*x = ", enum.GoIdent, "(num)")
Damien Neil46abb572018-09-07 12:45:37 -0700336 g.P("return nil")
337 g.P("}")
338 g.P()
339 }
340
Joe Tsai61968ce2019-04-01 12:59:24 -0700341 // EnumDescriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700342 if generateRawDescMethods {
343 var indexes []string
344 for i := 1; i < len(enum.Location.Path); i += 2 {
345 indexes = append(indexes, strconv.Itoa(int(enum.Location.Path[i])))
346 }
347 g.P("// Deprecated: Use ", enum.GoIdent, ".Type instead.")
348 g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {")
349 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
350 g.P("}")
351 g.P()
Damien Neil46abb572018-09-07 12:45:37 -0700352 }
Damien Neil46abb572018-09-07 12:45:37 -0700353
Damien Neilea7baf42018-09-28 14:23:44 -0700354 genWellKnownType(g, "", enum.GoIdent, enum.Desc)
Damien Neil46abb572018-09-07 12:45:37 -0700355}
356
Joe Tsai61968ce2019-04-01 12:59:24 -0700357// enumLegacyName returns the name used by the v1 proto package.
Damien Neil658051b2018-09-10 12:26:21 -0700358//
359// Confusingly, this is <proto_package>.<go_ident>. This probably should have
360// been the full name of the proto enum type instead, but changing it at this
361// point would require thought.
Joe Tsai61968ce2019-04-01 12:59:24 -0700362func enumLegacyName(enum *protogen.Enum) string {
Joe Tsai67c1d9b2019-05-12 02:27:46 -0700363 fdesc := enum.Desc.ParentFile()
Damien Neildaa4fad2018-10-08 14:08:27 -0700364 if fdesc.Package() == "" {
365 return enum.GoIdent.GoName
366 }
Damien Neil658051b2018-09-10 12:26:21 -0700367 return string(fdesc.Package()) + "." + enum.GoIdent.GoName
368}
369
Damien Neild39efc82018-09-24 12:38:10 -0700370func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Damien Neil0bd5a382018-09-13 15:07:10 -0700371 if message.Desc.IsMapEntry() {
372 return
373 }
374
Joe Tsai61968ce2019-04-01 12:59:24 -0700375 // Message type declaration.
Damien Neilba1159f2018-10-17 12:53:18 -0700376 hasComment := g.PrintLeadingComments(message.Location)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800377 if message.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700378 if hasComment {
379 g.P("//")
380 }
381 g.P(deprecationComment(true))
382 }
Damien Neil162c1272018-10-04 12:42:37 -0700383 g.Annotate(message.GoIdent.GoName, message.Location)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700384 g.P("type ", message.GoIdent, " struct {")
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700385 sf := f.allMessageFieldsByPtr[message]
Damien Neil658051b2018-09-10 12:26:21 -0700386 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700387 if field.Oneof != nil {
Damien Neil1fa78d82018-09-13 13:12:36 -0700388 // It would be a bit simpler to iterate over the oneofs below,
389 // but generating the field here keeps the contents of the Go
390 // struct in the same order as the contents of the source
391 // .proto file.
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700392 oneof := field.Oneof
393 if field != oneof.Fields[0] {
394 continue // already generated oneof field for first entry
Damien Neil1fa78d82018-09-13 13:12:36 -0700395 }
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700396 if g.PrintLeadingComments(oneof.Location) {
397 g.P("//")
398 }
399 g.P("// Types that are valid to be assigned to ", oneofFieldName(oneof), ":")
400 for _, field := range oneof.Fields {
401 g.PrintLeadingComments(field.Location)
402 g.P("//\t*", fieldOneofType(field))
403 }
404 g.Annotate(message.GoIdent.GoName+"."+oneofFieldName(oneof), oneof.Location)
405 g.P(oneofFieldName(oneof), " ", oneofInterfaceName(oneof), " `protobuf_oneof:\"", oneof.Desc.Name(), "\"`")
406 sf.append(oneofFieldName(oneof))
Damien Neil658051b2018-09-10 12:26:21 -0700407 continue
408 }
Damien Neilba1159f2018-10-17 12:53:18 -0700409 g.PrintLeadingComments(field.Location)
Damien Neil77f82fe2018-09-13 10:59:17 -0700410 goType, pointer := fieldGoType(g, field)
411 if pointer {
412 goType = "*" + goType
413 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700414 tags := []string{
415 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
416 fmt.Sprintf("json:%q", fieldJSONTag(field)),
417 }
418 if field.Desc.IsMap() {
Joe Tsaid24bc722019-04-15 23:39:09 -0700419 key := field.Message.Fields[0]
420 val := field.Message.Fields[1]
Damien Neil0bd5a382018-09-13 15:07:10 -0700421 tags = append(tags,
422 fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)),
423 fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)),
424 )
425 }
Damien Neil162c1272018-10-04 12:42:37 -0700426 g.Annotate(message.GoIdent.GoName+"."+field.GoName, field.Location)
Damien Neil55fe1c02018-09-17 15:11:24 -0700427 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`",
Joe Tsaie1f8d502018-11-26 18:55:29 -0800428 deprecationComment(field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()))
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700429 sf.append(field.GoName)
Damien Neil658051b2018-09-10 12:26:21 -0700430 }
Damien Neil993c04d2018-09-14 15:41:11 -0700431
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700432 if generateNoUnkeyedLiteralFields {
433 g.P("XXX_NoUnkeyedLiteral", " struct{} `json:\"-\"`")
434 sf.append("XXX_NoUnkeyedLiteral")
435 }
436 if generateExportedSizeCacheFields {
437 g.P("XXX_sizecache", " ", protoimplPackage.Ident("SizeCache"), " `json:\"-\"`")
438 sf.append("XXX_sizecache")
439 } else {
440 g.P("sizeCache", " ", protoimplPackage.Ident("SizeCache"))
441 sf.append("sizeCache")
442 }
443 if generateExportedUnknownFields {
444 g.P("XXX_unrecognized", " ", protoimplPackage.Ident("UnknownFields"), " `json:\"-\"`")
445 sf.append("XXX_unrecognized")
446 } else {
447 g.P("unknownFields", " ", protoimplPackage.Ident("UnknownFields"))
448 sf.append("unknownFields")
449 }
Damien Neil993c04d2018-09-14 15:41:11 -0700450 if message.Desc.ExtensionRanges().Len() > 0 {
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700451 // TODO: Remove this tag when we drop v1 support.
Damien Neil993c04d2018-09-14 15:41:11 -0700452 var tags []string
Joe Tsaie1f8d502018-11-26 18:55:29 -0800453 if message.Desc.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() {
Damien Neil993c04d2018-09-14 15:41:11 -0700454 tags = append(tags, `protobuf_messageset:"1"`)
455 }
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700456 if generateExportedExtensionFields {
457 tags = append(tags, `json:"-"`)
458 g.P("XXX_InternalExtensions", " ", protoimplPackage.Ident("ExtensionFields"), " `", strings.Join(tags, " "), "`")
459 sf.append("XXX_InternalExtensions")
460 } else {
461 g.P("extensionFields", " ", protoimplPackage.Ident("ExtensionFields"), " `", strings.Join(tags, " "), "`")
462 sf.append("extensionFields")
463 }
Damien Neil993c04d2018-09-14 15:41:11 -0700464 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700465 g.P("}")
466 g.P()
467
Joe Tsai61968ce2019-04-01 12:59:24 -0700468 // Reset method.
469 g.P("func (x *", message.GoIdent, ") Reset() {")
470 g.P("*x = ", message.GoIdent, "{}")
471 g.P("}")
472 g.P()
473 // String method.
474 g.P("func (x *", message.GoIdent, ") String() string {")
475 g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)")
476 g.P("}")
477 g.P()
478 // ProtoMessage method.
479 g.P("func (*", message.GoIdent, ") ProtoMessage() {}")
480 g.P()
481
Joe Tsaib6405bd2018-11-15 14:44:37 -0800482 genReflectMessage(gen, g, f, message)
483
Joe Tsai61968ce2019-04-01 12:59:24 -0700484 // Descriptor method.
Joe Tsaiab61d412019-04-16 15:23:29 -0700485 if generateRawDescMethods {
486 var indexes []string
487 for i := 1; i < len(message.Location.Path); i += 2 {
488 indexes = append(indexes, strconv.Itoa(int(message.Location.Path[i])))
489 }
490 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type instead.")
491 g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {")
492 g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}")
493 g.P("}")
494 g.P()
Damien Neila1c6abc2018-09-12 13:36:34 -0700495 }
Damien Neil993c04d2018-09-14 15:41:11 -0700496
Joe Tsai61968ce2019-04-01 12:59:24 -0700497 // ExtensionRangeArray method.
Damien Neil993c04d2018-09-14 15:41:11 -0700498 if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 {
Joe Tsai4fddeba2019-03-20 18:29:32 -0700499 protoExtRange := protoifacePackage.Ident("ExtensionRangeV1")
Damien Neil993c04d2018-09-14 15:41:11 -0700500 extRangeVar := "extRange_" + message.GoIdent.GoName
501 g.P("var ", extRangeVar, " = []", protoExtRange, " {")
502 for i := 0; i < extranges.Len(); i++ {
503 r := extranges.Get(i)
504 g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},")
505 }
506 g.P("}")
507 g.P()
Joe Tsai8e506a82019-03-16 00:05:34 -0700508 g.P("// Deprecated: Use ", message.GoIdent, ".ProtoReflect.Type.ExtensionRanges instead.")
Damien Neil993c04d2018-09-14 15:41:11 -0700509 g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {")
510 g.P("return ", extRangeVar)
511 g.P("}")
512 g.P()
513 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700514
Damien Neilea7baf42018-09-28 14:23:44 -0700515 genWellKnownType(g, "*", message.GoIdent, message.Desc)
516
Damien Neilebc699d2018-09-13 08:50:13 -0700517 // Constants and vars holding the default values of fields.
518 for _, field := range message.Fields {
Joe Tsai9667c482018-12-05 15:42:52 -0800519 if !field.Desc.HasDefault() {
Damien Neilebc699d2018-09-13 08:50:13 -0700520 continue
521 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700522 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neilebc699d2018-09-13 08:50:13 -0700523 def := field.Desc.Default()
524 switch field.Desc.Kind() {
525 case protoreflect.StringKind:
526 g.P("const ", defVarName, " string = ", strconv.Quote(def.String()))
527 case protoreflect.BytesKind:
528 g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")")
529 case protoreflect.EnumKind:
Damien Neila485fbd2018-10-26 13:28:37 -0700530 evalueDesc := field.Desc.DefaultEnumValue()
Joe Tsaid24bc722019-04-15 23:39:09 -0700531 enum := field.Enum
Damien Neila485fbd2018-10-26 13:28:37 -0700532 evalue := enum.Values[evalueDesc.Index()]
Joe Tsaid24bc722019-04-15 23:39:09 -0700533 g.P("const ", defVarName, " ", field.Enum.GoIdent, " = ", evalue.GoIdent)
Damien Neilebc699d2018-09-13 08:50:13 -0700534 case protoreflect.FloatKind, protoreflect.DoubleKind:
535 // Floating point numbers need extra handling for -Inf/Inf/NaN.
536 f := field.Desc.Default().Float()
537 goType := "float64"
538 if field.Desc.Kind() == protoreflect.FloatKind {
539 goType = "float32"
540 }
541 // funcCall returns a call to a function in the math package,
542 // possibly converting the result to float32.
543 funcCall := func(fn, param string) string {
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800544 s := g.QualifiedGoIdent(mathPackage.Ident(fn)) + param
Damien Neilebc699d2018-09-13 08:50:13 -0700545 if goType != "float64" {
546 s = goType + "(" + s + ")"
547 }
548 return s
549 }
550 switch {
551 case math.IsInf(f, -1):
552 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)"))
553 case math.IsInf(f, 1):
554 g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)"))
555 case math.IsNaN(f):
556 g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()"))
557 default:
Damien Neil982684b2018-09-28 14:12:41 -0700558 g.P("const ", defVarName, " ", goType, " = ", field.Desc.Default().Interface())
Damien Neilebc699d2018-09-13 08:50:13 -0700559 }
560 default:
Damien Neil77f82fe2018-09-13 10:59:17 -0700561 goType, _ := fieldGoType(g, field)
Damien Neilebc699d2018-09-13 08:50:13 -0700562 g.P("const ", defVarName, " ", goType, " = ", def.Interface())
563 }
564 }
565 g.P()
566
Joe Tsai61968ce2019-04-01 12:59:24 -0700567 // Getter methods.
Damien Neil77f82fe2018-09-13 10:59:17 -0700568 for _, field := range message.Fields {
Joe Tsai872b5002019-04-08 14:03:15 -0700569 if isFirstOneofField(field) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700570 genOneofGetter(gen, g, f, message, field.Oneof)
Damien Neil1fa78d82018-09-13 13:12:36 -0700571 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700572 goType, pointer := fieldGoType(g, field)
573 defaultValue := fieldDefaultValue(g, message, field)
Joe Tsaie1f8d502018-11-26 18:55:29 -0800574 if field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated() {
Damien Neil55fe1c02018-09-17 15:11:24 -0700575 g.P(deprecationComment(true))
576 }
Damien Neil162c1272018-10-04 12:42:37 -0700577 g.Annotate(message.GoIdent.GoName+".Get"+field.GoName, field.Location)
Joe Tsai61968ce2019-04-01 12:59:24 -0700578 g.P("func (x *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {")
Joe Tsaid24bc722019-04-15 23:39:09 -0700579 if field.Oneof != nil {
580 g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", fieldOneofType(field), "); ok {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700581 g.P("return x.", field.GoName)
582 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700583 } else {
Damien Neil1fa78d82018-09-13 13:12:36 -0700584 if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" {
Joe Tsai61968ce2019-04-01 12:59:24 -0700585 g.P("if x != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700586 } else {
Joe Tsai61968ce2019-04-01 12:59:24 -0700587 g.P("if x != nil && x.", field.GoName, " != nil {")
Damien Neil1fa78d82018-09-13 13:12:36 -0700588 }
589 star := ""
590 if pointer {
591 star = "*"
592 }
Joe Tsai61968ce2019-04-01 12:59:24 -0700593 g.P("return ", star, " x.", field.GoName)
Damien Neil1fa78d82018-09-13 13:12:36 -0700594 g.P("}")
Damien Neil77f82fe2018-09-13 10:59:17 -0700595 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700596 g.P("return ", defaultValue)
597 g.P("}")
598 g.P()
599 }
Damien Neila1c6abc2018-09-12 13:36:34 -0700600
Joe Tsai09912272019-07-08 10:38:11 -0700601 // Oneof wrapper types.
Damien Neil1fa78d82018-09-13 13:12:36 -0700602 if len(message.Oneofs) > 0 {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800603 genOneofWrappers(gen, g, f, message)
Damien Neil1fa78d82018-09-13 13:12:36 -0700604 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700605}
Damien Neilcab8dfe2018-09-06 14:51:28 -0700606
Damien Neil77f82fe2018-09-13 10:59:17 -0700607// fieldGoType returns the Go type used for a field.
608//
609// If it returns pointer=true, the struct field is a pointer to the type.
610func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) {
Damien Neil77f82fe2018-09-13 10:59:17 -0700611 pointer = true
Damien Neil658051b2018-09-10 12:26:21 -0700612 switch field.Desc.Kind() {
613 case protoreflect.BoolKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700614 goType = "bool"
Damien Neil658051b2018-09-10 12:26:21 -0700615 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700616 goType = g.QualifiedGoIdent(field.Enum.GoIdent)
Damien Neil658051b2018-09-10 12:26:21 -0700617 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700618 goType = "int32"
Damien Neil658051b2018-09-10 12:26:21 -0700619 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700620 goType = "uint32"
Damien Neil658051b2018-09-10 12:26:21 -0700621 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700622 goType = "int64"
Damien Neil658051b2018-09-10 12:26:21 -0700623 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700624 goType = "uint64"
Damien Neil658051b2018-09-10 12:26:21 -0700625 case protoreflect.FloatKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700626 goType = "float32"
Damien Neil658051b2018-09-10 12:26:21 -0700627 case protoreflect.DoubleKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700628 goType = "float64"
Damien Neil658051b2018-09-10 12:26:21 -0700629 case protoreflect.StringKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700630 goType = "string"
Damien Neil658051b2018-09-10 12:26:21 -0700631 case protoreflect.BytesKind:
Damien Neil77f82fe2018-09-13 10:59:17 -0700632 goType = "[]byte"
633 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700634 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700635 goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700636 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700637 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700638 switch {
639 case field.Desc.IsList():
Damien Neil77f82fe2018-09-13 10:59:17 -0700640 goType = "[]" + goType
641 pointer = false
Joe Tsaiac31a352019-05-13 14:32:56 -0700642 case field.Desc.IsMap():
643 keyType, _ := fieldGoType(g, field.Message.Fields[0])
644 valType, _ := fieldGoType(g, field.Message.Fields[1])
645 return fmt.Sprintf("map[%v]%v", keyType, valType), false
Damien Neil658051b2018-09-10 12:26:21 -0700646 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700647
Damien Neil44000a12018-10-24 12:31:16 -0700648 // Extension fields always have pointer type, even when defined in a proto3 file.
Joe Tsaiac31a352019-05-13 14:32:56 -0700649 if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700650 pointer = false
Damien Neil658051b2018-09-10 12:26:21 -0700651 }
Damien Neil77f82fe2018-09-13 10:59:17 -0700652 return goType, pointer
Damien Neil658051b2018-09-10 12:26:21 -0700653}
654
655func fieldProtobufTag(field *protogen.Field) string {
Joe Tsai05828db2018-11-01 13:52:16 -0700656 var enumName string
Damien Neil658051b2018-09-10 12:26:21 -0700657 if field.Desc.Kind() == protoreflect.EnumKind {
Joe Tsaid24bc722019-04-15 23:39:09 -0700658 enumName = enumLegacyName(field.Enum)
Damien Neil658051b2018-09-10 12:26:21 -0700659 }
Joe Tsai05828db2018-11-01 13:52:16 -0700660 return tag.Marshal(field.Desc, enumName)
Damien Neil658051b2018-09-10 12:26:21 -0700661}
662
Damien Neil77f82fe2018-09-13 10:59:17 -0700663func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
Joe Tsaiac31a352019-05-13 14:32:56 -0700664 if field.Desc.IsList() {
Damien Neil77f82fe2018-09-13 10:59:17 -0700665 return "nil"
666 }
Joe Tsai9667c482018-12-05 15:42:52 -0800667 if field.Desc.HasDefault() {
Damien Neil1fa78d82018-09-13 13:12:36 -0700668 defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName
Damien Neil77f82fe2018-09-13 10:59:17 -0700669 if field.Desc.Kind() == protoreflect.BytesKind {
670 return "append([]byte(nil), " + defVarName + "...)"
671 }
672 return defVarName
673 }
674 switch field.Desc.Kind() {
675 case protoreflect.BoolKind:
676 return "false"
677 case protoreflect.StringKind:
678 return `""`
679 case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind:
680 return "nil"
681 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700682 return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent)
Damien Neil77f82fe2018-09-13 10:59:17 -0700683 default:
684 return "0"
685 }
686}
687
Damien Neil658051b2018-09-10 12:26:21 -0700688func fieldJSONTag(field *protogen.Field) string {
689 return string(field.Desc.Name()) + ",omitempty"
690}
691
Joe Tsaiafb455e2019-03-14 16:08:22 -0700692func genExtensions(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) {
693 if len(f.allExtensions) == 0 {
694 return
Damien Neil154da982018-09-19 13:21:58 -0700695 }
696
Joe Tsaid8881392019-06-06 13:01:53 -0700697 g.P("var ", extDescsVarName(f), " = []", protoifacePackage.Ident("ExtensionDescV1"), "{")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700698 for _, extension := range f.allExtensions {
699 // Special case for proto2 message sets: If this extension is extending
700 // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
701 // then drop that last component.
702 //
703 // TODO: This should be implemented in the text formatter rather than the generator.
704 // In addition, the situation for when to apply this special case is implemented
705 // differently in other languages:
706 // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
707 name := extension.Desc.FullName()
708 if n, ok := isExtensionMessageSetElement(extension); ok {
709 name = n
710 }
711
712 g.P("{")
Joe Tsaid24bc722019-04-15 23:39:09 -0700713 g.P("ExtendedType: (*", extension.Extendee.GoIdent, ")(nil),")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700714 goType, pointer := fieldGoType(g, extension)
715 if pointer {
716 goType = "*" + goType
717 }
718 g.P("ExtensionType: (", goType, ")(nil),")
719 g.P("Field: ", extension.Desc.Number(), ",")
720 g.P("Name: ", strconv.Quote(string(name)), ",")
721 g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",")
722 g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",")
723 g.P("},")
Damien Neil993c04d2018-09-14 15:41:11 -0700724 }
Damien Neil993c04d2018-09-14 15:41:11 -0700725 g.P("}")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700726
727 g.P("var (")
728 for i, extension := range f.allExtensions {
729 ed := extension.Desc
Joe Tsaiac31a352019-05-13 14:32:56 -0700730 targetName := string(ed.ContainingMessage().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700731 typeName := ed.Kind().String()
732 switch ed.Kind() {
733 case protoreflect.EnumKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700734 typeName = string(ed.Enum().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700735 case protoreflect.MessageKind, protoreflect.GroupKind:
Joe Tsaid24bc722019-04-15 23:39:09 -0700736 typeName = string(ed.Message().FullName())
Joe Tsaiafb455e2019-03-14 16:08:22 -0700737 }
738 fieldName := string(ed.Name())
739 g.P("// extend ", targetName, " { ", ed.Cardinality().String(), " ", typeName, " ", fieldName, " = ", ed.Number(), "; }")
Joe Tsaid8881392019-06-06 13:01:53 -0700740 g.P(extensionVar(f.File, extension), " = &", extDescsVarName(f), "[", i, "]")
Joe Tsaiafb455e2019-03-14 16:08:22 -0700741 g.P()
742 }
743 g.P(")")
Damien Neil993c04d2018-09-14 15:41:11 -0700744}
745
Damien Neil62386962018-10-30 10:35:48 -0700746// isExtensionMessageSetELement returns the adjusted name of an extension
747// which extends proto2.bridge.MessageSet.
748func isExtensionMessageSetElement(extension *protogen.Extension) (name protoreflect.FullName, ok bool) {
Joe Tsaid24bc722019-04-15 23:39:09 -0700749 opts := extension.Extendee.Desc.Options().(*descriptorpb.MessageOptions)
Damien Neil62386962018-10-30 10:35:48 -0700750 if !opts.GetMessageSetWireFormat() || extension.Desc.Name() != "message_set_extension" {
751 return "", false
752 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700753 if extension.Parent == nil {
Damien Neil62386962018-10-30 10:35:48 -0700754 // This case shouldn't be given special handling at all--we're
755 // only supposed to drop the ".message_set_extension" for
756 // extensions defined within a message (i.e., the extension
757 // takes the message's name).
758 //
759 // This matches the behavior of the v1 generator, however.
760 //
761 // TODO: See if we can drop this case.
762 name = extension.Desc.FullName()
763 name = name[:len(name)-len("message_set_extension")]
764 return name, true
765 }
766 return extension.Desc.FullName().Parent(), true
Damien Neil154da982018-09-19 13:21:58 -0700767}
768
Damien Neil993c04d2018-09-14 15:41:11 -0700769// extensionVar returns the var holding the ExtensionDesc for an extension.
Damien Neil6b541312018-10-29 09:14:14 -0700770func extensionVar(f *protogen.File, extension *protogen.Extension) protogen.GoIdent {
Damien Neil993c04d2018-09-14 15:41:11 -0700771 name := "E_"
Joe Tsaid24bc722019-04-15 23:39:09 -0700772 if extension.Parent != nil {
773 name += extension.Parent.GoIdent.GoName + "_"
Damien Neil993c04d2018-09-14 15:41:11 -0700774 }
775 name += extension.GoName
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800776 return f.GoImportPath.Ident(name)
Damien Neil993c04d2018-09-14 15:41:11 -0700777}
778
Damien Neil55fe1c02018-09-17 15:11:24 -0700779// deprecationComment returns a standard deprecation comment if deprecated is true.
780func deprecationComment(deprecated bool) string {
781 if !deprecated {
782 return ""
783 }
784 return "// Deprecated: Do not use."
785}
786
Damien Neil5c5b5312019-05-14 12:44:37 -0700787// TODO: Remove this. This was added to aid protojson, but protojson does this work
Joe Tsai61968ce2019-04-01 12:59:24 -0700788// through the use of protobuf reflection now.
Damien Neilea7baf42018-09-28 14:23:44 -0700789func genWellKnownType(g *protogen.GeneratedFile, ptr string, ident protogen.GoIdent, desc protoreflect.Descriptor) {
Damien Neil46abb572018-09-07 12:45:37 -0700790 if wellKnownTypes[desc.FullName()] {
Damien Neilea7baf42018-09-28 14:23:44 -0700791 g.P("func (", ptr, ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`)
Damien Neil46abb572018-09-07 12:45:37 -0700792 g.P()
793 }
794}
795
796// Names of messages and enums for which we will generate XXX_WellKnownType methods.
797var wellKnownTypes = map[protoreflect.FullName]bool{
Damien Neilea7baf42018-09-28 14:23:44 -0700798 "google.protobuf.Any": true,
799 "google.protobuf.Duration": true,
800 "google.protobuf.Empty": true,
801 "google.protobuf.Struct": true,
802 "google.protobuf.Timestamp": true,
803
804 "google.protobuf.BoolValue": true,
805 "google.protobuf.BytesValue": true,
806 "google.protobuf.DoubleValue": true,
807 "google.protobuf.FloatValue": true,
808 "google.protobuf.Int32Value": true,
809 "google.protobuf.Int64Value": true,
810 "google.protobuf.ListValue": true,
811 "google.protobuf.NullValue": true,
812 "google.protobuf.StringValue": true,
813 "google.protobuf.UInt32Value": true,
814 "google.protobuf.UInt64Value": true,
815 "google.protobuf.Value": true,
Damien Neil46abb572018-09-07 12:45:37 -0700816}
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800817
Joe Tsai872b5002019-04-08 14:03:15 -0700818// genOneofGetter generate a Get method for a oneof.
819func genOneofGetter(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
820 g.Annotate(message.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location)
821 g.P("func (m *", message.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {")
822 g.P("if m != nil {")
823 g.P("return m.", oneofFieldName(oneof))
824 g.P("}")
825 g.P("return nil")
826 g.P("}")
827 g.P()
828}
829
Joe Tsai09912272019-07-08 10:38:11 -0700830// genOneofWrappers generates the oneof wrapper types and associates the types
831// with the parent message type.
Joe Tsai872b5002019-04-08 14:03:15 -0700832func genOneofWrappers(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message) {
Joe Tsai09912272019-07-08 10:38:11 -0700833 idx := f.allMessagesByPtr[message]
834 typesVar := messageTypesVarName(f)
835
836 // Associate the wrapper types through a XXX_OneofWrappers method.
837 if generateOneofWrapperMethods {
838 g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
839 g.P("func (*", message.GoIdent.GoName, ") XXX_OneofWrappers() []interface{} {")
840 g.P("return ", typesVar, "[", idx, "].OneofWrappers")
841 g.P("}")
842 g.P()
Joe Tsai872b5002019-04-08 14:03:15 -0700843 }
Joe Tsai09912272019-07-08 10:38:11 -0700844
845 // Generate the oneof wrapper types.
846 for _, oneof := range message.Oneofs {
847 genOneofTypes(gen, g, f, message, oneof)
848 }
Joe Tsai872b5002019-04-08 14:03:15 -0700849}
850
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800851// genOneofTypes generates the interface type used for a oneof field,
852// and the wrapper types that satisfy that interface.
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800853func genOneofTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, message *protogen.Message, oneof *protogen.Oneof) {
854 ifName := oneofInterfaceName(oneof)
855 g.P("type ", ifName, " interface {")
856 g.P(ifName, "()")
857 g.P("}")
858 g.P()
859 for _, field := range oneof.Fields {
860 name := fieldOneofType(field)
861 g.Annotate(name.GoName, field.Location)
862 g.Annotate(name.GoName+"."+field.GoName, field.Location)
863 g.P("type ", name, " struct {")
864 goType, _ := fieldGoType(g, field)
865 tags := []string{
866 fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)),
867 }
868 g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`")
869 g.P("}")
870 g.P()
871 }
872 for _, field := range oneof.Fields {
873 g.P("func (*", fieldOneofType(field), ") ", ifName, "() {}")
874 g.P()
875 }
Joe Tsai872b5002019-04-08 14:03:15 -0700876}
877
878// isFirstOneofField reports whether this is the first field in a oneof.
879func isFirstOneofField(field *protogen.Field) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700880 return field.Oneof != nil && field.Oneof.Fields[0] == field
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800881}
882
883// oneofFieldName returns the name of the struct field holding the oneof value.
884//
885// This function is trivial, but pulling out the name like this makes it easier
886// to experiment with alternative oneof implementations.
887func oneofFieldName(oneof *protogen.Oneof) string {
888 return oneof.GoName
889}
890
891// oneofInterfaceName returns the name of the interface type implemented by
892// the oneof field value types.
893func oneofInterfaceName(oneof *protogen.Oneof) string {
Joe Tsaid24bc722019-04-15 23:39:09 -0700894 return fmt.Sprintf("is%s_%s", oneof.Parent.GoIdent.GoName, oneof.GoName)
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800895}
896
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800897// fieldOneofType returns the wrapper type used to represent a field in a oneof.
898func fieldOneofType(field *protogen.Field) protogen.GoIdent {
899 ident := protogen.GoIdent{
Joe Tsaid24bc722019-04-15 23:39:09 -0700900 GoImportPath: field.Parent.GoIdent.GoImportPath,
901 GoName: field.Parent.GoIdent.GoName + "_" + field.GoName,
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800902 }
903 // Check for collisions with nested messages or enums.
904 //
905 // This conflict resolution is incomplete: Among other things, it
906 // does not consider collisions with other oneof field types.
907 //
908 // TODO: Consider dropping this entirely. Detecting conflicts and
909 // producing an error is almost certainly better than permuting
910 // field and type names in mostly unpredictable ways.
911Loop:
912 for {
Joe Tsaid24bc722019-04-15 23:39:09 -0700913 for _, message := range field.Parent.Messages {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800914 if message.GoIdent == ident {
915 ident.GoName += "_"
916 continue Loop
917 }
918 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700919 for _, enum := range field.Parent.Enums {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800920 if enum.GoIdent == ident {
921 ident.GoName += "_"
922 continue Loop
923 }
924 }
925 return ident
926 }
927}