Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 1 | // 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 | |
| 5 | // The protoc-gen-go binary is a protoc plugin to generate a Go protocol |
| 6 | // buffer package. |
| 7 | package main |
| 8 | |
| 9 | import ( |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 10 | "bytes" |
| 11 | "compress/gzip" |
| 12 | "crypto/sha256" |
| 13 | "encoding/hex" |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 14 | "flag" |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 15 | "fmt" |
Damien Neil | ebc699d | 2018-09-13 08:50:13 -0700 | [diff] [blame] | 16 | "math" |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 17 | "sort" |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 18 | "strconv" |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 19 | "strings" |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 20 | |
| 21 | "github.com/golang/protobuf/proto" |
| 22 | descpb "github.com/golang/protobuf/protoc-gen-go/descriptor" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 23 | "google.golang.org/proto/protogen" |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 24 | "google.golang.org/proto/reflect/protoreflect" |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 25 | ) |
| 26 | |
Damien Neil | d412792 | 2018-09-12 11:13:49 -0700 | [diff] [blame] | 27 | // generatedCodeVersion indicates a version of the generated code. |
| 28 | // It is incremented whenever an incompatibility between the generated code and |
| 29 | // proto package is introduced; the generated code references |
| 30 | // a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion). |
| 31 | const generatedCodeVersion = 2 |
| 32 | |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 33 | const protoPackage = "github.com/golang/protobuf/proto" |
| 34 | |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 35 | func main() { |
Damien Neil | 3cf6e62 | 2018-09-11 13:53:14 -0700 | [diff] [blame] | 36 | var flags flag.FlagSet |
| 37 | // TODO: Decide what to do for backwards compatibility with plugins=grpc. |
| 38 | flags.String("plugins", "", "") |
| 39 | opts := &protogen.Options{ |
| 40 | ParamFunc: flags.Set, |
| 41 | } |
| 42 | protogen.Run(opts, func(gen *protogen.Plugin) error { |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 43 | for _, f := range gen.Files { |
| 44 | if !f.Generate { |
| 45 | continue |
| 46 | } |
| 47 | genFile(gen, f) |
| 48 | } |
| 49 | return nil |
| 50 | }) |
| 51 | } |
| 52 | |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 53 | type File struct { |
| 54 | *protogen.File |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 55 | locationMap map[string][]*descpb.SourceCodeInfo_Location |
| 56 | descriptorVar string // var containing the gzipped FileDescriptorProto |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 57 | allEnums []*protogen.Enum |
| 58 | allMessages []*protogen.Message |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 59 | allExtensions []*protogen.Extension |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 60 | } |
| 61 | |
| 62 | func genFile(gen *protogen.Plugin, file *protogen.File) { |
| 63 | f := &File{ |
| 64 | File: file, |
| 65 | locationMap: make(map[string][]*descpb.SourceCodeInfo_Location), |
| 66 | } |
| 67 | for _, loc := range file.Proto.GetSourceCodeInfo().GetLocation() { |
| 68 | key := pathKey(loc.Path) |
| 69 | f.locationMap[key] = append(f.locationMap[key], loc) |
| 70 | } |
| 71 | |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 72 | // The different order for enums and extensions is to match the output |
| 73 | // of the previous implementation. |
| 74 | // |
| 75 | // TODO: Eventually make this consistent. |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 76 | f.allEnums = append(f.allEnums, f.File.Enums...) |
Damien Neil | 73ac885 | 2018-09-17 15:11:24 -0700 | [diff] [blame] | 77 | walkMessages(f.Messages, func(message *protogen.Message) { |
| 78 | f.allMessages = append(f.allMessages, message) |
| 79 | f.allEnums = append(f.allEnums, message.Enums...) |
| 80 | f.allExtensions = append(f.allExtensions, message.Extensions...) |
| 81 | }) |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 82 | f.allExtensions = append(f.allExtensions, f.File.Extensions...) |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 83 | |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 84 | // Determine the name of the var holding the file descriptor: |
| 85 | // |
| 86 | // fileDescriptor_<hash of filename> |
| 87 | filenameHash := sha256.Sum256([]byte(f.Desc.Path())) |
| 88 | f.descriptorVar = fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(filenameHash[:8])) |
| 89 | |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 90 | g := gen.NewGeneratedFile(f.GeneratedFilenamePrefix+".pb.go", f.GoImportPath) |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 91 | g.P("// Code generated by protoc-gen-go. DO NOT EDIT.") |
Damien Neil | abc6fc1 | 2018-08-23 14:39:30 -0700 | [diff] [blame] | 92 | g.P("// source: ", f.Desc.Path()) |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 93 | g.P() |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 94 | const filePackageField = 2 // FileDescriptorProto.package |
| 95 | genComment(g, f, []int32{filePackageField}) |
| 96 | g.P() |
Damien Neil | 082ce92 | 2018-09-06 10:23:53 -0700 | [diff] [blame] | 97 | g.P("package ", f.GoPackageName) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 98 | g.P() |
Damien Neil | 1ec3315 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 99 | |
| 100 | // These references are not necessary, since we automatically add |
| 101 | // all necessary imports before formatting the generated file. |
| 102 | // |
| 103 | // This section exists to generate output more consistent with |
| 104 | // the previous version of protoc-gen-go, to make it easier to |
| 105 | // detect unintended variations. |
| 106 | // |
| 107 | // TODO: Eventually remove this. |
| 108 | g.P("// Reference imports to suppress errors if they are not otherwise used.") |
| 109 | g.P("var _ = ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "Marshal"}) |
| 110 | g.P("var _ = ", protogen.GoIdent{GoImportPath: "fmt", GoName: "Errorf"}) |
| 111 | g.P("var _ = ", protogen.GoIdent{GoImportPath: "math", GoName: "Inf"}) |
| 112 | g.P() |
| 113 | |
Damien Neil | d412792 | 2018-09-12 11:13:49 -0700 | [diff] [blame] | 114 | g.P("// This is a compile-time assertion to ensure that this generated file") |
| 115 | g.P("// is compatible with the proto package it is being compiled against.") |
| 116 | g.P("// A compilation error at this line likely means your copy of the") |
| 117 | g.P("// proto package needs to be updated.") |
| 118 | g.P("const _ = ", protogen.GoIdent{ |
| 119 | GoImportPath: protoPackage, |
| 120 | GoName: fmt.Sprintf("ProtoPackageIsVersion%d", generatedCodeVersion), |
| 121 | }, "// please upgrade the proto package") |
| 122 | g.P() |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 123 | |
Damien Neil | 73ac885 | 2018-09-17 15:11:24 -0700 | [diff] [blame] | 124 | for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ { |
| 125 | genImport(gen, g, f, imps.Get(i)) |
| 126 | } |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 127 | for _, enum := range f.allEnums { |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 128 | genEnum(gen, g, f, enum) |
| 129 | } |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 130 | for _, message := range f.allMessages { |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 131 | genMessage(gen, g, f, message) |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 132 | } |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 133 | for _, extension := range f.Extensions { |
| 134 | genExtension(gen, g, f, extension) |
| 135 | } |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 136 | |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 137 | genInitFunction(gen, g, f) |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 138 | |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 139 | genFileDescriptor(gen, g, f) |
| 140 | } |
| 141 | |
Damien Neil | 73ac885 | 2018-09-17 15:11:24 -0700 | [diff] [blame] | 142 | // walkMessages calls f on each message and all of its descendants. |
| 143 | func walkMessages(messages []*protogen.Message, f func(*protogen.Message)) { |
| 144 | for _, m := range messages { |
| 145 | f(m) |
| 146 | walkMessages(m.Messages, f) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, imp protoreflect.FileImport) { |
Damien Neil | 73ac885 | 2018-09-17 15:11:24 -0700 | [diff] [blame] | 151 | impFile, ok := gen.FileByName(imp.Path()) |
| 152 | if !ok { |
| 153 | return |
| 154 | } |
| 155 | if impFile.GoImportPath == f.GoImportPath { |
Damien Neil | 2e0c3da | 2018-09-19 12:51:36 -0700 | [diff] [blame^] | 156 | // Don't generate imports or aliases for types in the same Go package. |
| 157 | return |
| 158 | } |
| 159 | // Generate imports for all dependencies, even if they are not |
| 160 | // referenced, because other code and tools depend on having the |
| 161 | // full transitive closure of protocol buffer types in the binary. |
| 162 | g.Import(impFile.GoImportPath) |
| 163 | if !imp.IsPublic { |
Damien Neil | 73ac885 | 2018-09-17 15:11:24 -0700 | [diff] [blame] | 164 | return |
| 165 | } |
| 166 | var enums []*protogen.Enum |
| 167 | enums = append(enums, impFile.Enums...) |
| 168 | walkMessages(impFile.Messages, func(message *protogen.Message) { |
| 169 | enums = append(enums, message.Enums...) |
| 170 | g.P("// ", message.GoIdent.GoName, " from public import ", imp.Path()) |
| 171 | g.P("type ", message.GoIdent.GoName, " = ", message.GoIdent) |
| 172 | for _, oneof := range message.Oneofs { |
| 173 | for _, field := range oneof.Fields { |
| 174 | typ := fieldOneofType(field) |
| 175 | g.P("type ", typ.GoName, " = ", typ) |
| 176 | } |
| 177 | } |
| 178 | g.P() |
| 179 | }) |
| 180 | for _, enum := range enums { |
| 181 | g.P("// ", enum.GoIdent.GoName, " from public import ", imp.Path()) |
| 182 | g.P("type ", enum.GoIdent.GoName, " = ", enum.GoIdent) |
| 183 | g.P("var ", enum.GoIdent.GoName, "_name = ", enum.GoIdent, "_name") |
| 184 | g.P("var ", enum.GoIdent.GoName, "_value = ", enum.GoIdent, "_value") |
| 185 | g.P() |
| 186 | for _, value := range enum.Values { |
| 187 | g.P("const ", value.GoIdent.GoName, " = ", enum.GoIdent.GoName, "(", value.GoIdent, ")") |
| 188 | } |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 189 | } |
| 190 | } |
| 191 | |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 192 | func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) { |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 193 | // Trim the source_code_info from the descriptor. |
| 194 | // Marshal and gzip it. |
| 195 | descProto := proto.Clone(f.Proto).(*descpb.FileDescriptorProto) |
| 196 | descProto.SourceCodeInfo = nil |
| 197 | b, err := proto.Marshal(descProto) |
| 198 | if err != nil { |
| 199 | gen.Error(err) |
| 200 | return |
| 201 | } |
| 202 | var buf bytes.Buffer |
| 203 | w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression) |
| 204 | w.Write(b) |
| 205 | w.Close() |
| 206 | b = buf.Bytes() |
| 207 | |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 208 | g.P("func init() { proto.RegisterFile(", strconv.Quote(f.Desc.Path()), ", ", f.descriptorVar, ") }") |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 209 | g.P() |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 210 | g.P("var ", f.descriptorVar, " = []byte{") |
Damien Neil | 7779e05 | 2018-09-07 14:14:06 -0700 | [diff] [blame] | 211 | g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto") |
| 212 | for len(b) > 0 { |
| 213 | n := 16 |
| 214 | if n > len(b) { |
| 215 | n = len(b) |
| 216 | } |
| 217 | |
| 218 | s := "" |
| 219 | for _, c := range b[:n] { |
| 220 | s += fmt.Sprintf("0x%02x,", c) |
| 221 | } |
| 222 | g.P(s) |
| 223 | |
| 224 | b = b[n:] |
| 225 | } |
| 226 | g.P("}") |
| 227 | g.P() |
Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame] | 228 | } |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 229 | |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 230 | func genEnum(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, enum *protogen.Enum) { |
| 231 | genComment(g, f, enum.Path) |
| 232 | // TODO: deprecation |
| 233 | g.P("type ", enum.GoIdent, " int32") |
| 234 | g.P("const (") |
| 235 | for _, value := range enum.Values { |
| 236 | genComment(g, f, value.Path) |
| 237 | // TODO: deprecation |
| 238 | g.P(value.GoIdent, " ", enum.GoIdent, " = ", value.Desc.Number()) |
| 239 | } |
| 240 | g.P(")") |
| 241 | g.P() |
| 242 | nameMap := enum.GoIdent.GoName + "_name" |
| 243 | g.P("var ", nameMap, " = map[int32]string{") |
| 244 | generated := make(map[protoreflect.EnumNumber]bool) |
| 245 | for _, value := range enum.Values { |
| 246 | duplicate := "" |
| 247 | if _, present := generated[value.Desc.Number()]; present { |
| 248 | duplicate = "// Duplicate value: " |
| 249 | } |
| 250 | g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",") |
| 251 | generated[value.Desc.Number()] = true |
| 252 | } |
| 253 | g.P("}") |
| 254 | g.P() |
| 255 | valueMap := enum.GoIdent.GoName + "_value" |
| 256 | g.P("var ", valueMap, " = map[string]int32{") |
| 257 | for _, value := range enum.Values { |
| 258 | g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",") |
| 259 | } |
| 260 | g.P("}") |
| 261 | g.P() |
| 262 | if enum.Desc.Syntax() != protoreflect.Proto3 { |
| 263 | g.P("func (x ", enum.GoIdent, ") Enum() *", enum.GoIdent, " {") |
| 264 | g.P("p := new(", enum.GoIdent, ")") |
| 265 | g.P("*p = x") |
| 266 | g.P("return p") |
| 267 | g.P("}") |
| 268 | g.P() |
| 269 | } |
| 270 | g.P("func (x ", enum.GoIdent, ") String() string {") |
| 271 | g.P("return ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "EnumName"}, "(", enum.GoIdent, "_name, int32(x))") |
| 272 | g.P("}") |
| 273 | g.P() |
| 274 | |
| 275 | if enum.Desc.Syntax() != protoreflect.Proto3 { |
| 276 | g.P("func (x *", enum.GoIdent, ") UnmarshalJSON(data []byte) error {") |
| 277 | g.P("value, err := ", protogen.GoIdent{GoImportPath: protoPackage, GoName: "UnmarshalJSONEnum"}, "(", enum.GoIdent, `_value, data, "`, enum.GoIdent, `")`) |
| 278 | g.P("if err != nil {") |
| 279 | g.P("return err") |
| 280 | g.P("}") |
| 281 | g.P("*x = ", enum.GoIdent, "(value)") |
| 282 | g.P("return nil") |
| 283 | g.P("}") |
| 284 | g.P() |
| 285 | } |
| 286 | |
| 287 | var indexes []string |
| 288 | for i := 1; i < len(enum.Path); i += 2 { |
| 289 | indexes = append(indexes, strconv.Itoa(int(enum.Path[i]))) |
| 290 | } |
| 291 | g.P("func (", enum.GoIdent, ") EnumDescriptor() ([]byte, []int) {") |
| 292 | g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}") |
| 293 | g.P("}") |
| 294 | g.P() |
| 295 | |
| 296 | genWellKnownType(g, enum.GoIdent, enum.Desc) |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 297 | } |
| 298 | |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 299 | // enumRegistryName returns the name used to register an enum with the proto |
| 300 | // package registry. |
| 301 | // |
| 302 | // Confusingly, this is <proto_package>.<go_ident>. This probably should have |
| 303 | // been the full name of the proto enum type instead, but changing it at this |
| 304 | // point would require thought. |
| 305 | func enumRegistryName(enum *protogen.Enum) string { |
| 306 | // Find the FileDescriptor for this enum. |
| 307 | var desc protoreflect.Descriptor = enum.Desc |
| 308 | for { |
| 309 | p, ok := desc.Parent() |
| 310 | if !ok { |
| 311 | break |
| 312 | } |
| 313 | desc = p |
| 314 | } |
| 315 | fdesc := desc.(protoreflect.FileDescriptor) |
| 316 | return string(fdesc.Package()) + "." + enum.GoIdent.GoName |
| 317 | } |
| 318 | |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 319 | func genMessage(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, message *protogen.Message) { |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 320 | if message.Desc.IsMapEntry() { |
| 321 | return |
| 322 | } |
| 323 | |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 324 | genComment(g, f, message.Path) |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 325 | // TODO: deprecation |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 326 | g.P("type ", message.GoIdent, " struct {") |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 327 | for _, field := range message.Fields { |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 328 | if field.OneofType != nil { |
| 329 | // It would be a bit simpler to iterate over the oneofs below, |
| 330 | // but generating the field here keeps the contents of the Go |
| 331 | // struct in the same order as the contents of the source |
| 332 | // .proto file. |
| 333 | if field == field.OneofType.Fields[0] { |
| 334 | genOneofField(gen, g, f, message, field.OneofType) |
| 335 | } |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 336 | continue |
| 337 | } |
| 338 | genComment(g, f, field.Path) |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 339 | goType, pointer := fieldGoType(g, field) |
| 340 | if pointer { |
| 341 | goType = "*" + goType |
| 342 | } |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 343 | tags := []string{ |
| 344 | fmt.Sprintf("protobuf:%q", fieldProtobufTag(field)), |
| 345 | fmt.Sprintf("json:%q", fieldJSONTag(field)), |
| 346 | } |
| 347 | if field.Desc.IsMap() { |
| 348 | key := field.MessageType.Fields[0] |
| 349 | val := field.MessageType.Fields[1] |
| 350 | tags = append(tags, |
| 351 | fmt.Sprintf("protobuf_key:%q", fieldProtobufTag(key)), |
| 352 | fmt.Sprintf("protobuf_val:%q", fieldProtobufTag(val)), |
| 353 | ) |
| 354 | } |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 355 | g.P(field.GoName, " ", goType, " `", strings.Join(tags, " "), "`") |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 356 | } |
| 357 | g.P("XXX_NoUnkeyedLiteral struct{} `json:\"-\"`") |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 358 | |
| 359 | if message.Desc.ExtensionRanges().Len() > 0 { |
| 360 | var tags []string |
| 361 | if messageOptions(gen, message).GetMessageSetWireFormat() { |
| 362 | tags = append(tags, `protobuf_messageset:"1"`) |
| 363 | } |
| 364 | tags = append(tags, `json:"-"`) |
| 365 | g.P(protogen.GoIdent{ |
| 366 | GoImportPath: protoPackage, |
| 367 | GoName: "XXX_InternalExtensions", |
| 368 | }, " `", strings.Join(tags, " "), "`") |
| 369 | } |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 370 | // TODO XXX_InternalExtensions |
| 371 | g.P("XXX_unrecognized []byte `json:\"-\"`") |
| 372 | g.P("XXX_sizecache int32 `json:\"-\"`") |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 373 | g.P("}") |
| 374 | g.P() |
| 375 | |
Damien Neil | a1c6abc | 2018-09-12 13:36:34 -0700 | [diff] [blame] | 376 | // Reset |
| 377 | g.P("func (m *", message.GoIdent, ") Reset() { *m = ", message.GoIdent, "{} }") |
| 378 | // String |
| 379 | g.P("func (m *", message.GoIdent, ") String() string { return ", protogen.GoIdent{ |
| 380 | GoImportPath: protoPackage, |
| 381 | GoName: "CompactTextString", |
| 382 | }, "(m) }") |
| 383 | // ProtoMessage |
| 384 | g.P("func (*", message.GoIdent, ") ProtoMessage() {}") |
| 385 | // Descriptor |
| 386 | var indexes []string |
| 387 | for i := 1; i < len(message.Path); i += 2 { |
| 388 | indexes = append(indexes, strconv.Itoa(int(message.Path[i]))) |
| 389 | } |
| 390 | g.P("func (*", message.GoIdent, ") Descriptor() ([]byte, []int) {") |
| 391 | g.P("return ", f.descriptorVar, ", []int{", strings.Join(indexes, ","), "}") |
| 392 | g.P("}") |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 393 | g.P() |
| 394 | |
| 395 | // ExtensionRangeArray |
| 396 | if extranges := message.Desc.ExtensionRanges(); extranges.Len() > 0 { |
| 397 | if messageOptions(gen, message).GetMessageSetWireFormat() { |
| 398 | g.P("func (m *", message.GoIdent, ") MarshalJSON() ([]byte, error) {") |
| 399 | g.P("return ", protogen.GoIdent{ |
| 400 | GoImportPath: protoPackage, |
| 401 | GoName: "MarshalMessageSetJSON", |
| 402 | }, "(&m.XXX_InternalExtensions)") |
| 403 | g.P("}") |
| 404 | g.P("func (m *", message.GoIdent, ") UnmarshalJSON(buf []byte) error {") |
| 405 | g.P("return ", protogen.GoIdent{ |
| 406 | GoImportPath: protoPackage, |
| 407 | GoName: "UnmarshalMessageSetJSON", |
| 408 | }, "(buf, &m.XXX_InternalExtensions)") |
| 409 | g.P("}") |
| 410 | g.P() |
| 411 | } |
| 412 | |
| 413 | protoExtRange := protogen.GoIdent{ |
| 414 | GoImportPath: protoPackage, |
| 415 | GoName: "ExtensionRange", |
| 416 | } |
| 417 | extRangeVar := "extRange_" + message.GoIdent.GoName |
| 418 | g.P("var ", extRangeVar, " = []", protoExtRange, " {") |
| 419 | for i := 0; i < extranges.Len(); i++ { |
| 420 | r := extranges.Get(i) |
| 421 | g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},") |
| 422 | } |
| 423 | g.P("}") |
| 424 | g.P() |
| 425 | g.P("func (*", message.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {") |
| 426 | g.P("return ", extRangeVar) |
| 427 | g.P("}") |
| 428 | g.P() |
| 429 | } |
Damien Neil | a1c6abc | 2018-09-12 13:36:34 -0700 | [diff] [blame] | 430 | |
| 431 | // Table-driven proto support. |
| 432 | // |
| 433 | // TODO: It does not scale to keep adding another method for every |
| 434 | // operation on protos that we want to switch over to using the |
| 435 | // table-driven approach. Instead, we should only add a single method |
| 436 | // that allows getting access to the *InternalMessageInfo struct and then |
| 437 | // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that. |
| 438 | messageInfoVar := "xxx_messageInfo_" + message.GoIdent.GoName |
| 439 | // XXX_Unmarshal |
| 440 | g.P("func (m *", message.GoIdent, ") XXX_Unmarshal(b []byte) error {") |
| 441 | g.P("return ", messageInfoVar, ".Unmarshal(m, b)") |
| 442 | g.P("}") |
| 443 | // XXX_Marshal |
| 444 | g.P("func (m *", message.GoIdent, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {") |
| 445 | g.P("return ", messageInfoVar, ".Marshal(b, m, deterministic)") |
| 446 | g.P("}") |
| 447 | // XXX_Merge |
| 448 | g.P("func (m *", message.GoIdent, ") XXX_Merge(src proto.Message) {") |
| 449 | g.P(messageInfoVar, ".Merge(m, src)") |
| 450 | g.P("}") |
| 451 | // XXX_Size |
| 452 | g.P("func (m *", message.GoIdent, ") XXX_Size() int {") |
| 453 | g.P("return ", messageInfoVar, ".Size(m)") |
| 454 | g.P("}") |
| 455 | // XXX_DiscardUnknown |
| 456 | g.P("func (m *", message.GoIdent, ") XXX_DiscardUnknown() {") |
| 457 | g.P(messageInfoVar, ".DiscardUnknown(m)") |
| 458 | g.P("}") |
| 459 | g.P() |
| 460 | g.P("var ", messageInfoVar, " ", protogen.GoIdent{ |
| 461 | GoImportPath: protoPackage, |
| 462 | GoName: "InternalMessageInfo", |
| 463 | }) |
| 464 | g.P() |
| 465 | |
Damien Neil | ebc699d | 2018-09-13 08:50:13 -0700 | [diff] [blame] | 466 | // Constants and vars holding the default values of fields. |
| 467 | for _, field := range message.Fields { |
| 468 | if !field.Desc.HasDefault() { |
| 469 | continue |
| 470 | } |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 471 | defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName |
Damien Neil | ebc699d | 2018-09-13 08:50:13 -0700 | [diff] [blame] | 472 | def := field.Desc.Default() |
| 473 | switch field.Desc.Kind() { |
| 474 | case protoreflect.StringKind: |
| 475 | g.P("const ", defVarName, " string = ", strconv.Quote(def.String())) |
| 476 | case protoreflect.BytesKind: |
| 477 | g.P("var ", defVarName, " []byte = []byte(", strconv.Quote(string(def.Bytes())), ")") |
| 478 | case protoreflect.EnumKind: |
| 479 | enum := field.EnumType |
| 480 | evalue := enum.Values[enum.Desc.Values().ByNumber(def.Enum()).Index()] |
| 481 | g.P("const ", defVarName, " ", field.EnumType.GoIdent, " = ", evalue.GoIdent) |
| 482 | case protoreflect.FloatKind, protoreflect.DoubleKind: |
| 483 | // Floating point numbers need extra handling for -Inf/Inf/NaN. |
| 484 | f := field.Desc.Default().Float() |
| 485 | goType := "float64" |
| 486 | if field.Desc.Kind() == protoreflect.FloatKind { |
| 487 | goType = "float32" |
| 488 | } |
| 489 | // funcCall returns a call to a function in the math package, |
| 490 | // possibly converting the result to float32. |
| 491 | funcCall := func(fn, param string) string { |
| 492 | s := g.QualifiedGoIdent(protogen.GoIdent{ |
| 493 | GoImportPath: "math", |
| 494 | GoName: fn, |
| 495 | }) + param |
| 496 | if goType != "float64" { |
| 497 | s = goType + "(" + s + ")" |
| 498 | } |
| 499 | return s |
| 500 | } |
| 501 | switch { |
| 502 | case math.IsInf(f, -1): |
| 503 | g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(-1)")) |
| 504 | case math.IsInf(f, 1): |
| 505 | g.P("var ", defVarName, " ", goType, " = ", funcCall("Inf", "(1)")) |
| 506 | case math.IsNaN(f): |
| 507 | g.P("var ", defVarName, " ", goType, " = ", funcCall("NaN", "()")) |
| 508 | default: |
| 509 | g.P("const ", defVarName, " ", goType, " = ", f) |
| 510 | } |
| 511 | default: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 512 | goType, _ := fieldGoType(g, field) |
Damien Neil | ebc699d | 2018-09-13 08:50:13 -0700 | [diff] [blame] | 513 | g.P("const ", defVarName, " ", goType, " = ", def.Interface()) |
| 514 | } |
| 515 | } |
| 516 | g.P() |
| 517 | |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 518 | // Getters. |
| 519 | for _, field := range message.Fields { |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 520 | if field.OneofType != nil { |
| 521 | if field == field.OneofType.Fields[0] { |
| 522 | genOneofTypes(gen, g, f, message, field.OneofType) |
| 523 | } |
| 524 | } |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 525 | goType, pointer := fieldGoType(g, field) |
| 526 | defaultValue := fieldDefaultValue(g, message, field) |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 527 | g.P("func (m *", message.GoIdent, ") Get", field.GoName, "() ", goType, " {") |
| 528 | if field.OneofType != nil { |
| 529 | g.P("if x, ok := m.Get", field.OneofType.GoName, "().(*", message.GoIdent.GoName, "_", field.GoName, "); ok {") |
| 530 | g.P("return x.", field.GoName) |
| 531 | g.P("}") |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 532 | } else { |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 533 | if field.Desc.Syntax() == protoreflect.Proto3 || defaultValue == "nil" { |
| 534 | g.P("if m != nil {") |
| 535 | } else { |
| 536 | g.P("if m != nil && m.", field.GoName, " != nil {") |
| 537 | } |
| 538 | star := "" |
| 539 | if pointer { |
| 540 | star = "*" |
| 541 | } |
| 542 | g.P("return ", star, " m.", field.GoName) |
| 543 | g.P("}") |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 544 | } |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 545 | g.P("return ", defaultValue) |
| 546 | g.P("}") |
| 547 | g.P() |
| 548 | } |
Damien Neil | a1c6abc | 2018-09-12 13:36:34 -0700 | [diff] [blame] | 549 | |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 550 | genWellKnownType(g, message.GoIdent, message.Desc) |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 551 | |
| 552 | if len(message.Oneofs) > 0 { |
| 553 | genOneofFuncs(gen, g, f, message) |
| 554 | } |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 555 | for _, extension := range message.Extensions { |
| 556 | genExtension(gen, g, f, extension) |
| 557 | } |
Damien Neil | c7d07d9 | 2018-08-22 13:46:02 -0700 | [diff] [blame] | 558 | } |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 559 | |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 560 | // fieldGoType returns the Go type used for a field. |
| 561 | // |
| 562 | // If it returns pointer=true, the struct field is a pointer to the type. |
| 563 | func fieldGoType(g *protogen.GeneratedFile, field *protogen.Field) (goType string, pointer bool) { |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 564 | pointer = true |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 565 | switch field.Desc.Kind() { |
| 566 | case protoreflect.BoolKind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 567 | goType = "bool" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 568 | case protoreflect.EnumKind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 569 | goType = g.QualifiedGoIdent(field.EnumType.GoIdent) |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 570 | case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 571 | goType = "int32" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 572 | case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 573 | goType = "uint32" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 574 | case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 575 | goType = "int64" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 576 | case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 577 | goType = "uint64" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 578 | case protoreflect.FloatKind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 579 | goType = "float32" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 580 | case protoreflect.DoubleKind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 581 | goType = "float64" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 582 | case protoreflect.StringKind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 583 | goType = "string" |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 584 | case protoreflect.BytesKind: |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 585 | goType = "[]byte" |
| 586 | pointer = false |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 587 | case protoreflect.MessageKind, protoreflect.GroupKind: |
Damien Neil | 0bd5a38 | 2018-09-13 15:07:10 -0700 | [diff] [blame] | 588 | if field.Desc.IsMap() { |
| 589 | keyType, _ := fieldGoType(g, field.MessageType.Fields[0]) |
| 590 | valType, _ := fieldGoType(g, field.MessageType.Fields[1]) |
| 591 | return fmt.Sprintf("map[%v]%v", keyType, valType), false |
| 592 | } |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 593 | goType = "*" + g.QualifiedGoIdent(field.MessageType.GoIdent) |
| 594 | pointer = false |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 595 | } |
| 596 | if field.Desc.Cardinality() == protoreflect.Repeated { |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 597 | goType = "[]" + goType |
| 598 | pointer = false |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 599 | } |
| 600 | if field.Desc.Syntax() == protoreflect.Proto3 { |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 601 | pointer = false |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 602 | } |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 603 | return goType, pointer |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 604 | } |
| 605 | |
| 606 | func fieldProtobufTag(field *protogen.Field) string { |
| 607 | var tag []string |
| 608 | // wire type |
| 609 | tag = append(tag, wireTypes[field.Desc.Kind()]) |
| 610 | // field number |
| 611 | tag = append(tag, strconv.Itoa(int(field.Desc.Number()))) |
| 612 | // cardinality |
| 613 | switch field.Desc.Cardinality() { |
| 614 | case protoreflect.Optional: |
| 615 | tag = append(tag, "opt") |
| 616 | case protoreflect.Required: |
| 617 | tag = append(tag, "req") |
| 618 | case protoreflect.Repeated: |
| 619 | tag = append(tag, "rep") |
| 620 | } |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 621 | // TODO: packed |
| 622 | // name |
| 623 | name := string(field.Desc.Name()) |
| 624 | if field.Desc.Kind() == protoreflect.GroupKind { |
| 625 | // The name of the FieldDescriptor for a group field is |
| 626 | // lowercased. To find the original capitalization, we |
| 627 | // look in the field's MessageType. |
| 628 | name = string(field.MessageType.Desc.Name()) |
| 629 | } |
| 630 | tag = append(tag, "name="+name) |
| 631 | // JSON name |
| 632 | if jsonName := field.Desc.JSONName(); jsonName != "" && jsonName != name { |
| 633 | tag = append(tag, "json="+jsonName) |
| 634 | } |
| 635 | // proto3 |
| 636 | if field.Desc.Syntax() == protoreflect.Proto3 { |
| 637 | tag = append(tag, "proto3") |
| 638 | } |
| 639 | // enum |
| 640 | if field.Desc.Kind() == protoreflect.EnumKind { |
| 641 | tag = append(tag, "enum="+enumRegistryName(field.EnumType)) |
| 642 | } |
| 643 | // oneof |
| 644 | if field.Desc.OneofType() != nil { |
| 645 | tag = append(tag, "oneof") |
| 646 | } |
Damien Neil | ebc699d | 2018-09-13 08:50:13 -0700 | [diff] [blame] | 647 | // default value |
| 648 | // This must appear last in the tag, since commas in strings aren't escaped. |
| 649 | if field.Desc.HasDefault() { |
| 650 | var def string |
| 651 | switch field.Desc.Kind() { |
| 652 | case protoreflect.BoolKind: |
| 653 | if field.Desc.Default().Bool() { |
| 654 | def = "1" |
| 655 | } else { |
| 656 | def = "0" |
| 657 | } |
| 658 | case protoreflect.BytesKind: |
| 659 | def = string(field.Desc.Default().Bytes()) |
| 660 | case protoreflect.FloatKind, protoreflect.DoubleKind: |
| 661 | f := field.Desc.Default().Float() |
| 662 | switch { |
| 663 | case math.IsInf(f, -1): |
| 664 | def = "-inf" |
| 665 | case math.IsInf(f, 1): |
| 666 | def = "inf" |
| 667 | case math.IsNaN(f): |
| 668 | def = "nan" |
| 669 | default: |
| 670 | def = fmt.Sprint(f) |
| 671 | } |
| 672 | default: |
| 673 | def = fmt.Sprint(field.Desc.Default().Interface()) |
| 674 | } |
| 675 | tag = append(tag, "def="+def) |
| 676 | } |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 677 | return strings.Join(tag, ",") |
| 678 | } |
| 679 | |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 680 | func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string { |
| 681 | if field.Desc.Cardinality() == protoreflect.Repeated { |
| 682 | return "nil" |
| 683 | } |
| 684 | if field.Desc.HasDefault() { |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 685 | defVarName := "Default_" + message.GoIdent.GoName + "_" + field.GoName |
Damien Neil | 77f82fe | 2018-09-13 10:59:17 -0700 | [diff] [blame] | 686 | if field.Desc.Kind() == protoreflect.BytesKind { |
| 687 | return "append([]byte(nil), " + defVarName + "...)" |
| 688 | } |
| 689 | return defVarName |
| 690 | } |
| 691 | switch field.Desc.Kind() { |
| 692 | case protoreflect.BoolKind: |
| 693 | return "false" |
| 694 | case protoreflect.StringKind: |
| 695 | return `""` |
| 696 | case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind: |
| 697 | return "nil" |
| 698 | case protoreflect.EnumKind: |
| 699 | return g.QualifiedGoIdent(field.EnumType.Values[0].GoIdent) |
| 700 | default: |
| 701 | return "0" |
| 702 | } |
| 703 | } |
| 704 | |
Damien Neil | 658051b | 2018-09-10 12:26:21 -0700 | [diff] [blame] | 705 | var wireTypes = map[protoreflect.Kind]string{ |
| 706 | protoreflect.BoolKind: "varint", |
| 707 | protoreflect.EnumKind: "varint", |
| 708 | protoreflect.Int32Kind: "varint", |
| 709 | protoreflect.Sint32Kind: "zigzag32", |
| 710 | protoreflect.Uint32Kind: "varint", |
| 711 | protoreflect.Int64Kind: "varint", |
| 712 | protoreflect.Sint64Kind: "zigzag64", |
| 713 | protoreflect.Uint64Kind: "varint", |
| 714 | protoreflect.Sfixed32Kind: "fixed32", |
| 715 | protoreflect.Fixed32Kind: "fixed32", |
| 716 | protoreflect.FloatKind: "fixed32", |
| 717 | protoreflect.Sfixed64Kind: "fixed64", |
| 718 | protoreflect.Fixed64Kind: "fixed64", |
| 719 | protoreflect.DoubleKind: "fixed64", |
| 720 | protoreflect.StringKind: "bytes", |
| 721 | protoreflect.BytesKind: "bytes", |
| 722 | protoreflect.MessageKind: "bytes", |
| 723 | protoreflect.GroupKind: "group", |
| 724 | } |
| 725 | |
| 726 | func fieldJSONTag(field *protogen.Field) string { |
| 727 | return string(field.Desc.Name()) + ",omitempty" |
| 728 | } |
| 729 | |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 730 | func genExtension(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File, extension *protogen.Extension) { |
| 731 | g.P("var ", extensionVar(f, extension), " = &", protogen.GoIdent{ |
| 732 | GoImportPath: protoPackage, |
| 733 | GoName: "ExtensionDesc", |
| 734 | }, "{") |
| 735 | g.P("ExtendedType: (*", extension.ExtendedType.GoIdent, ")(nil),") |
| 736 | goType, pointer := fieldGoType(g, extension) |
| 737 | if pointer { |
| 738 | goType = "*" + goType |
| 739 | } |
| 740 | g.P("ExtensionType: (", goType, ")(nil),") |
| 741 | g.P("Field: ", extension.Desc.Number(), ",") |
| 742 | g.P("Name: ", strconv.Quote(string(extension.Desc.FullName())), ",") |
| 743 | g.P("Tag: ", strconv.Quote(fieldProtobufTag(extension)), ",") |
| 744 | g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",") |
| 745 | g.P("}") |
| 746 | g.P() |
| 747 | } |
| 748 | |
| 749 | // extensionVar returns the var holding the ExtensionDesc for an extension. |
| 750 | func extensionVar(f *File, extension *protogen.Extension) protogen.GoIdent { |
| 751 | name := "E_" |
| 752 | if extension.ParentMessage != nil { |
| 753 | name += extension.ParentMessage.GoIdent.GoName + "_" |
| 754 | } |
| 755 | name += extension.GoName |
| 756 | return protogen.GoIdent{ |
| 757 | GoImportPath: f.GoImportPath, |
| 758 | GoName: name, |
| 759 | } |
| 760 | } |
| 761 | |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 762 | // genInitFunction generates an init function that registers the types in the |
| 763 | // generated file with the proto package. |
| 764 | func genInitFunction(gen *protogen.Plugin, g *protogen.GeneratedFile, f *File) { |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 765 | if len(f.allMessages) == 0 && len(f.allEnums) == 0 && len(f.allExtensions) == 0 { |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 766 | return |
| 767 | } |
| 768 | |
| 769 | g.P("func init() {") |
| 770 | for _, message := range f.allMessages { |
| 771 | if message.Desc.IsMapEntry() { |
| 772 | continue |
| 773 | } |
| 774 | |
| 775 | name := message.GoIdent.GoName |
| 776 | g.P(protogen.GoIdent{ |
| 777 | GoImportPath: protoPackage, |
| 778 | GoName: "RegisterType", |
| 779 | }, fmt.Sprintf("((*%s)(nil), %q)", name, message.Desc.FullName())) |
| 780 | |
| 781 | // Types of map fields, sorted by the name of the field message type. |
| 782 | var mapFields []*protogen.Field |
| 783 | for _, field := range message.Fields { |
| 784 | if field.Desc.IsMap() { |
| 785 | mapFields = append(mapFields, field) |
| 786 | } |
| 787 | } |
| 788 | sort.Slice(mapFields, func(i, j int) bool { |
| 789 | ni := mapFields[i].MessageType.Desc.FullName() |
| 790 | nj := mapFields[j].MessageType.Desc.FullName() |
| 791 | return ni < nj |
| 792 | }) |
| 793 | for _, field := range mapFields { |
| 794 | typeName := string(field.MessageType.Desc.FullName()) |
| 795 | goType, _ := fieldGoType(g, field) |
| 796 | g.P(protogen.GoIdent{ |
| 797 | GoImportPath: protoPackage, |
| 798 | GoName: "RegisterMapType", |
| 799 | }, fmt.Sprintf("((%v)(nil), %q)", goType, typeName)) |
| 800 | } |
| 801 | } |
| 802 | for _, enum := range f.allEnums { |
| 803 | name := enum.GoIdent.GoName |
| 804 | g.P(protogen.GoIdent{ |
| 805 | GoImportPath: protoPackage, |
| 806 | GoName: "RegisterEnum", |
| 807 | }, fmt.Sprintf("(%q, %s_name, %s_value)", enumRegistryName(enum), name, name)) |
| 808 | } |
Damien Neil | 993c04d | 2018-09-14 15:41:11 -0700 | [diff] [blame] | 809 | for _, extension := range f.allExtensions { |
| 810 | g.P(protogen.GoIdent{ |
| 811 | GoImportPath: protoPackage, |
| 812 | GoName: "RegisterExtension", |
| 813 | }, "(", extensionVar(f, extension), ")") |
| 814 | } |
Damien Neil | ce36f8d | 2018-09-13 15:19:08 -0700 | [diff] [blame] | 815 | g.P("}") |
| 816 | g.P() |
| 817 | } |
| 818 | |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 819 | func genComment(g *protogen.GeneratedFile, f *File, path []int32) (hasComment bool) { |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 820 | for _, loc := range f.locationMap[pathKey(path)] { |
| 821 | if loc.LeadingComments == nil { |
| 822 | continue |
| 823 | } |
| 824 | for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") { |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 825 | hasComment = true |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 826 | g.P("//", line) |
| 827 | } |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 828 | break |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 829 | } |
Damien Neil | 1fa78d8 | 2018-09-13 13:12:36 -0700 | [diff] [blame] | 830 | return hasComment |
Damien Neil | cab8dfe | 2018-09-06 14:51:28 -0700 | [diff] [blame] | 831 | } |
| 832 | |
| 833 | // pathKey converts a location path to a string suitable for use as a map key. |
| 834 | func pathKey(path []int32) string { |
| 835 | var buf []byte |
| 836 | for i, x := range path { |
| 837 | if i != 0 { |
| 838 | buf = append(buf, ',') |
| 839 | } |
| 840 | buf = strconv.AppendInt(buf, int64(x), 10) |
| 841 | } |
| 842 | return string(buf) |
| 843 | } |
Damien Neil | 46abb57 | 2018-09-07 12:45:37 -0700 | [diff] [blame] | 844 | |
| 845 | func genWellKnownType(g *protogen.GeneratedFile, ident protogen.GoIdent, desc protoreflect.Descriptor) { |
| 846 | if wellKnownTypes[desc.FullName()] { |
| 847 | g.P("func (", ident, `) XXX_WellKnownType() string { return "`, desc.Name(), `" }`) |
| 848 | g.P() |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | // Names of messages and enums for which we will generate XXX_WellKnownType methods. |
| 853 | var wellKnownTypes = map[protoreflect.FullName]bool{ |
| 854 | "google.protobuf.NullValue": true, |
| 855 | } |