Skip to content

Commit d3de96c

Browse files
authored
protoc-gen-go: normalize floating-point default values (#737)
Parse floating-point default values and format them with fmt.Sprint. Eliminates a minor point of inconsistency with the v2 generator.
1 parent 5e0eda4 commit d3de96c

File tree

3 files changed

+157
-66
lines changed

3 files changed

+157
-66
lines changed

protoc-gen-go/generator/generator.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1536,6 +1536,18 @@ func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptor
15361536
g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName()))
15371537
}
15381538
defaultValue = enum.integerValueAsString(defaultValue)
1539+
case descriptor.FieldDescriptorProto_TYPE_FLOAT:
1540+
if def := defaultValue; def != "inf" && def != "-inf" && def != "nan" {
1541+
if f, err := strconv.ParseFloat(defaultValue, 32); err == nil {
1542+
defaultValue = fmt.Sprint(float32(f))
1543+
}
1544+
}
1545+
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
1546+
if def := defaultValue; def != "inf" && def != "-inf" && def != "nan" {
1547+
if f, err := strconv.ParseFloat(defaultValue, 64); err == nil {
1548+
defaultValue = fmt.Sprint(f)
1549+
}
1550+
}
15391551
}
15401552
defaultValue = ",def=" + defaultValue
15411553
}
@@ -2235,6 +2247,14 @@ func (g *Generator) generateDefaultConstants(mc *msgCtx, topLevelFields []topLev
22352247
def = "float32(" + def + ")"
22362248
}
22372249
kind = "var "
2250+
case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_FLOAT:
2251+
if f, err := strconv.ParseFloat(def, 32); err == nil {
2252+
def = fmt.Sprint(float32(f))
2253+
}
2254+
case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_DOUBLE:
2255+
if f, err := strconv.ParseFloat(def, 64); err == nil {
2256+
def = fmt.Sprint(f)
2257+
}
22382258
case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_ENUM:
22392259
// Must be an enum. Need to construct the prefixed name.
22402260
obj := g.ObjectNamed(df.getProtoTypeName())

protoc-gen-go/testdata/my_test/test.pb.go

Lines changed: 130 additions & 66 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

protoc-gen-go/testdata/my_test/test.proto

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,13 @@ message Request {
8585
optional int32 reset = 12;
8686
// This field should not conflict with any getters.
8787
optional string get_key = 16;
88+
89+
optional float float_ninf = 20 [default=-inf];
90+
optional float float_pinf = 21 [default=inf];
91+
optional float float_exp = 22 [default=1e9];
92+
optional double double_ninf = 23 [default=-inf];
93+
optional double double_pinf = 24 [default=inf];
94+
optional double double_exp = 25 [default=1e9];
8895
}
8996

9097
message Reply {

0 commit comments

Comments
 (0)