From 575963eedfde91f86522b9ce969156cb36d3e3a5 Mon Sep 17 00:00:00 2001 From: sdghchj Date: Tue, 18 Jul 2023 14:47:40 +0800 Subject: [PATCH] parse binary literal const (#1593) * support binary const Signed-off-by: sdghchj * add test Signed-off-by: sdghchj --------- Signed-off-by: sdghchj --- enums_test.go | 3 ++- package.go | 28 ++++++++++++++-------------- testdata/enums/consts/const.go | 1 + 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/enums_test.go b/enums_test.go index dbae10d83..e3456378e 100644 --- a/enums_test.go +++ b/enums_test.go @@ -28,5 +28,6 @@ func TestParseGlobalEnums(t *testing.T) { assert.Equal(t, 15, p.packages.packages[constsPath].ConstTable["octnum"].Value) assert.Equal(t, `aa\nbb\u8888cc`, p.packages.packages[constsPath].ConstTable["nonescapestr"].Value) assert.Equal(t, "aa\nbb\u8888cc", p.packages.packages[constsPath].ConstTable["escapestr"].Value) - assert.Equal(t, '\u8888', p.packages.packages[constsPath].ConstTable["escapechar"].Value) + assert.Equal(t, 1_000_000, p.packages.packages[constsPath].ConstTable["underscored"].Value) + assert.Equal(t, 0b10001000, p.packages.packages[constsPath].ConstTable["binaryInteger"].Value) } diff --git a/package.go b/package.go index 6b4e3bd0d..6c3129e52 100644 --- a/package.go +++ b/package.go @@ -99,22 +99,22 @@ func (pkg *PackageDefinitions) evaluateConstValue(file *ast.File, iota int, expr if strings.ContainsRune(valueExpr.Value, '_') { valueExpr.Value = strings.Replace(valueExpr.Value, "_", "", -1) } - // hexadecimal - if len(valueExpr.Value) > 2 && valueExpr.Value[0] == '0' && valueExpr.Value[1] == 'x' { - if x, err := strconv.ParseInt(valueExpr.Value[2:], 16, 64); err == nil { - return int(x), nil - } else if x, err := strconv.ParseUint(valueExpr.Value[2:], 16, 64); err == nil { - return x, nil - } else { - panic(err) + if len(valueExpr.Value) >= 2 && valueExpr.Value[0] == '0' { + var start, base = 2, 8 + switch valueExpr.Value[1] { + case 'x', 'X': + //hex + base = 16 + case 'b', 'B': + //binary + base = 2 + default: + //octet + start = 1 } - } - - //octet - if len(valueExpr.Value) > 1 && valueExpr.Value[0] == '0' { - if x, err := strconv.ParseInt(valueExpr.Value[1:], 8, 64); err == nil { + if x, err := strconv.ParseInt(valueExpr.Value[start:], base, 64); err == nil { return int(x), nil - } else if x, err := strconv.ParseUint(valueExpr.Value[1:], 8, 64); err == nil { + } else if x, err := strconv.ParseUint(valueExpr.Value[start:], base, 64); err == nil { return x, nil } else { panic(err) diff --git a/testdata/enums/consts/const.go b/testdata/enums/consts/const.go index 27bfb28f5..fd718d121 100644 --- a/testdata/enums/consts/const.go +++ b/testdata/enums/consts/const.go @@ -11,3 +11,4 @@ const nonescapestr = `aa\nbb\u8888cc` const escapestr = "aa\nbb\u8888cc" const escapechar = '\u8888' const underscored = 1_000_000 +const binaryInteger = 0b10001000