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