Skip to content

Commit

Permalink
parse binary literal const (#1593)
Browse files Browse the repository at this point in the history
* support binary const

Signed-off-by: sdghchj <sdghchj@qq.com>

* add test

Signed-off-by: sdghchj <sdghchj@qq.com>

---------

Signed-off-by: sdghchj <sdghchj@qq.com>
  • Loading branch information
sdghchj authored Jul 18, 2023
1 parent 4536bf2 commit 575963e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 15 deletions.
3 changes: 2 additions & 1 deletion enums_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
28 changes: 14 additions & 14 deletions package.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions testdata/enums/consts/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 575963e

Please sign in to comment.