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