Skip to content

Commit

Permalink
Fix %v formatting (#181)
Browse files Browse the repository at this point in the history
* Fix %v formatting

* Added Bytes

* Fixed tests.
  • Loading branch information
geseq authored and d5 committed Apr 10, 2019
1 parent 09009d4 commit 3eebecb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
14 changes: 12 additions & 2 deletions stdlib/fmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,12 @@ func fmtPrintf(args ...objects.Object) (ret objects.Object, err error) {

formatArgs := make([]interface{}, numArgs-1, numArgs-1)
for idx, arg := range args[1:] {
formatArgs[idx] = objects.ToInterface(arg)
switch arg := arg.(type) {
case *objects.Int, *objects.Float, *objects.Bool, *objects.Char, *objects.String, *objects.Bytes:
formatArgs[idx] = objects.ToInterface(arg)
default:
formatArgs[idx] = arg
}
}

fmt.Printf(format.Value, formatArgs...)
Expand Down Expand Up @@ -86,7 +91,12 @@ func fmtSprintf(args ...objects.Object) (ret objects.Object, err error) {

formatArgs := make([]interface{}, numArgs-1, numArgs-1)
for idx, arg := range args[1:] {
formatArgs[idx] = objects.ToInterface(arg)
switch arg := arg.(type) {
case *objects.Int, *objects.Float, *objects.Bool, *objects.Char, *objects.String, *objects.Bytes:
formatArgs[idx] = objects.ToInterface(arg)
default:
formatArgs[idx] = arg
}
}

s := fmt.Sprintf(format.Value, formatArgs...)
Expand Down
6 changes: 4 additions & 2 deletions stdlib/fmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ func TestFmtSprintf(t *testing.T) {
module(t, `fmt`).call("sprintf", "").expect("")
module(t, `fmt`).call("sprintf", "foo").expect("foo")
module(t, `fmt`).call("sprintf", `foo %d %v %s`, 1, 2, "bar").expect("foo 1 2 bar")
module(t, `fmt`).call("sprintf", "foo %v", `[1, "bar", true]`).expect(`foo [1, "bar", true]`)
module(t, `fmt`).call("sprintf", "foo %v %d", `[1, "bar", true]`, 19).expect(`foo [1, "bar", true] 19`)
module(t, `fmt`).call("sprintf", "foo %v", ARR{1, "bar", true}).expect(`foo [1, "bar", true]`)
module(t, `fmt`).call("sprintf", "foo %v %d", ARR{1, "bar", true}, 19).expect(`foo [1, "bar", true] 19`)
module(t, `fmt`).call("sprintf", "foo %v", MAP{"a": IMAP{"b": IMAP{"c": ARR{1, 2, 3}}}}).expect(`foo {a: {b: {c: [1, 2, 3]}}}`)
module(t, `fmt`).call("sprintf", "%v", IARR{1, IARR{2, IARR{3, 4}}}).expect(`[1, [2, [3, 4]]]`)
}

0 comments on commit 3eebecb

Please sign in to comment.