in protoc-gen-go/generator/generator.go [1341:1432]
func (g *Generator) generateEnum(enum *EnumDescriptor) {
// The full type name
typeName := enum.TypeName()
// The full type name, CamelCased.
ccTypeName := CamelCaseSlice(typeName)
ccPrefix := enum.prefix()
deprecatedEnum := ""
if enum.GetOptions().GetDeprecated() {
deprecatedEnum = deprecationComment
}
g.PrintComments(enum.path)
g.P("type ", Annotate(enum.file, enum.path, ccTypeName), " int32", deprecatedEnum)
g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()})
g.P("const (")
for i, e := range enum.Value {
etorPath := fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i)
g.PrintComments(etorPath)
deprecatedValue := ""
if e.GetOptions().GetDeprecated() {
deprecatedValue = deprecationComment
}
name := ccPrefix + *e.Name
g.P(Annotate(enum.file, etorPath, name), " ", ccTypeName, " = ", e.Number, " ", deprecatedValue)
g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName})
}
g.P(")")
g.P()
g.P("var ", ccTypeName, "_name = map[int32]string{")
generated := make(map[int32]bool) // avoid duplicate values
for _, e := range enum.Value {
duplicate := ""
if _, present := generated[*e.Number]; present {
duplicate = "// Duplicate value: "
}
g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",")
generated[*e.Number] = true
}
g.P("}")
g.P()
g.P("var ", ccTypeName, "_value = map[string]int32{")
for _, e := range enum.Value {
g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
}
g.P("}")
g.P()
if !enum.proto3() {
g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {")
g.P("p := new(", ccTypeName, ")")
g.P("*p = x")
g.P("return p")
g.P("}")
g.P()
}
g.P("func (x ", ccTypeName, ") String() string {")
g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))")
g.P("}")
g.P()
if !enum.proto3() {
g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {")
g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`)
g.P("if err != nil {")
g.P("return err")
g.P("}")
g.P("*x = ", ccTypeName, "(value)")
g.P("return nil")
g.P("}")
g.P()
}
var indexes []string
for m := enum.parent; m != nil; m = m.parent {
// XXX: skip groups?
indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
}
indexes = append(indexes, strconv.Itoa(enum.index))
g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) {")
g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
g.P("}")
g.P()
if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" {
g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`)
g.P()
}
g.generateEnumRegistration(enum)
}