Skip to content

fix: std.format accepts boolean for numeric conversion codes#233

Open
He-Pin wants to merge 1 commit into
deltarocks:masterfrom
He-Pin:fix-format-boolean-coercion
Open

fix: std.format accepts boolean for numeric conversion codes#233
He-Pin wants to merge 1 commit into
deltarocks:masterfrom
He-Pin:fix-format-boolean-coercion

Conversation

@He-Pin

@He-Pin He-Pin commented Jun 26, 2026

Copy link
Copy Markdown

Summary

The official Jsonnet spec states:

The string formatting follows the same rules as Python.

In Python, bool is a subclass of int, so "%d" % True returns "1". However, jrsonnet currently rejects booleans for all numeric conversion codes with type error: expected number, got boolean.

This fix coerces Val::Bool(true) to Val::Num(1.0) and Val::Bool(false) to Val::Num(0.0) before numeric conversion in format_code(), matching Python's behavior.

The %s conversion is intentionally left unchanged, as Python's "%s" % True returns "True" (not "1").

Related upstream PRs: google/jsonnet#1328, google/go-jsonnet#884

Before / After

Expression Python jrsonnet (before) jrsonnet (after)
"%d" % true "1" ERROR "1"
"%f" % false "0.000000" ERROR "0.000000"
"%x" % true "1" ERROR "1"
"%o" % true "1" ERROR "1"
"%e" % true "1.000000e+00" ERROR "1.000000e+00"
"%g" % true "1" ERROR "1"
"%c" % true "\x01" ERROR "\x01"
"%s" % true "True" "true" "true" (unchanged)

Test plan

  • Existing format tests continue to pass (cargo test -p jrsonnet-evaluator -- 7/7 passed)
  • Boolean coercion matches Python's bool -> int behavior for all numeric codes (%d, %o, %x, %e, %f, %g)
  • Boolean coercion applied for %c (character code) matching Python
  • %s conversion unaffected -- booleans still render as "true"/"false"

The official Jsonnet spec states that std.format follows Python's
string formatting rules. In Python, bool is a subclass of int, so
"%d" % True returns "1". This fix coerces boolean values to 0.0/1.0
before processing numeric conversion codes, matching Python's behavior.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant