Skip to content

Commit

Permalink
starlark: treat {+1} in format string as key not number (google#115)
Browse files Browse the repository at this point in the history
  • Loading branch information
adonovan authored Jan 15, 2019
1 parent 339c281 commit bf3b587
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
18 changes: 17 additions & 1 deletion starlark/library.go
Original file line number Diff line number Diff line change
Expand Up @@ -1724,7 +1724,7 @@ func string_format(fnname string, recv_ Value, args Tuple, kwargs []Tuple) (Valu
}
arg = args[index]
index++
} else if num, err := strconv.Atoi(name); err == nil && !strings.HasPrefix(name, "-") {
} else if num, ok := decimal(name); ok {
// positional argument
if auto {
return nil, fmt.Errorf("cannot switch from automatic field numbering to manual field specification")
Expand Down Expand Up @@ -1780,6 +1780,22 @@ func string_format(fnname string, recv_ Value, args Tuple, kwargs []Tuple) (Valu
return String(buf.String()), nil
}

// decimal interprets s as a sequence of decimal digits.
func decimal(s string) (x int, ok bool) {
n := len(s)
for i := 0; i < n; i++ {
digit := s[i] - '0'
if digit > 9 {
return 0, false
}
x = x*10 + int(digit)
if x < 0 {
return 0, false // underflow
}
}
return x, true
}

// https://github.com/google/starlark-go/blob/master/doc/spec.md#string·index
func string_index(fnname string, recv Value, args Tuple, kwargs []Tuple) (Value, error) {
return string_find_impl(fnname, string(recv.(String)), args, kwargs, false, false)
Expand Down
4 changes: 4 additions & 0 deletions starlark/testdata/string.star
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ assert.eq("a{x}b{y}c{}".format(1, x=2, y=3), "a2b3c1")
assert.fails(lambda: "a{z}b".format(x=1), "keyword z not found")
assert.fails(lambda: "{-1}".format(1), "keyword -1 not found")
assert.fails(lambda: "{-0}".format(1), "keyword -0 not found")
assert.fails(lambda: "{+0}".format(1), "keyword \\+0 not found")
assert.fails(lambda: "{+1}".format(1), "keyword \\+1 not found") # starlark-go/issues/114
assert.eq("{0000000000001}".format(0, 1), "1")
assert.eq("{012}".format(*range(100)), "12") # decimal, despite leading zeros
assert.fails(lambda: '{0,1} and {1}'.format(1, 2), "keyword 0,1 not found")
assert.fails(lambda: "a{123}b".format(), "tuple index out of range")
assert.fails(lambda: "a{}b{}c".format(1), "tuple index out of range")
Expand Down

0 comments on commit bf3b587

Please sign in to comment.