Skip to content

Commit b71ea43

Browse files
authored
fix: parse oct const error (#2100)
strconv.ParseInt can handle integer literal correctly with base=0.
1 parent 2d060f7 commit b71ea43

File tree

3 files changed

+4
-29
lines changed

3 files changed

+4
-29
lines changed

enums_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ func TestParseGlobalEnums(t *testing.T) {
3333
assert.Equal(t, "aa\nbb\u8888cc", p.packages.packages[constsPath].ConstTable["escapestr"].Value)
3434
assert.Equal(t, 1_000_000, p.packages.packages[constsPath].ConstTable["underscored"].Value)
3535
assert.Equal(t, 0b10001000, p.packages.packages[constsPath].ConstTable["binaryInteger"].Value)
36+
assert.Equal(t, 0o755, p.packages.packages[constsPath].ConstTable["octInteger"].Value)
3637

3738
typesPath := "github.com/swaggo/swag/testdata/enums/types"
3839

package.go

Lines changed: 2 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"go/token"
66
"reflect"
77
"strconv"
8-
"strings"
98
)
109

1110
// PackageDefinitions files and definition in a package.
@@ -100,36 +99,10 @@ func (pkg *PackageDefinitions) evaluateConstValue(file *ast.File, iota int, expr
10099
case *ast.BasicLit:
101100
switch valueExpr.Kind {
102101
case token.INT:
103-
// handle underscored number, such as 1_000_000
104-
if strings.ContainsRune(valueExpr.Value, '_') {
105-
valueExpr.Value = strings.Replace(valueExpr.Value, "_", "", -1)
106-
}
107-
if len(valueExpr.Value) >= 2 && valueExpr.Value[0] == '0' {
108-
var start, base = 2, 8
109-
switch valueExpr.Value[1] {
110-
case 'x', 'X':
111-
//hex
112-
base = 16
113-
case 'b', 'B':
114-
//binary
115-
base = 2
116-
default:
117-
//octet
118-
start = 1
119-
}
120-
if x, err := strconv.ParseInt(valueExpr.Value[start:], base, 64); err == nil {
121-
return int(x), nil
122-
} else if x, err := strconv.ParseUint(valueExpr.Value[start:], base, 64); err == nil {
123-
return x, nil
124-
} else {
125-
panic(err)
126-
}
127-
}
128-
129102
//a basic literal integer is int type in default, or must have an explicit converting type in front
130-
if x, err := strconv.ParseInt(valueExpr.Value, 10, 64); err == nil {
103+
if x, err := strconv.ParseInt(valueExpr.Value, 0, 64); err == nil {
131104
return int(x), nil
132-
} else if x, err := strconv.ParseUint(valueExpr.Value, 10, 64); err == nil {
105+
} else if x, err := strconv.ParseUint(valueExpr.Value, 0, 64); err == nil {
133106
return x, nil
134107
} else {
135108
panic(err)

testdata/enums/consts/const.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ const escapestr = "aa\nbb\u8888cc"
1212
const escapechar = '\u8888'
1313
const underscored = 1_000_000
1414
const binaryInteger = 0b10001000
15+
const octInteger = 0o755

0 commit comments

Comments
 (0)