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