Skip to content

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

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

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

Conversation

@He-Pin

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

Copy link
Copy Markdown
Contributor

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, go-jsonnet currently rejects booleans for all numeric conversion codes with Format required number at N, got boolean.

This fix coerces boolean values to 0/1 in format_code() before numeric conversion, matching Python's behavior.

Upstream PR: google/jsonnet#1328

Before / After

Expression Python go-jsonnet (before) go-jsonnet (after)
"%d" % true "1" ERROR "1"
"%f" % false "0.000000" ERROR "0.000000"
"%x" % true "1" ERROR "1"
"%s" % true "True" "true" "true"

Changes

  • stdlib/std.jsonnet: Added boolean-to-number coercion in format_code(). The %s branch is handled first (before coercion) so %s with true still returns "true". All numeric branches (d, o, x, f, e, g, c) use num_val which coerces booleans to 0/1.
  • astgen/stdast.go: Regenerated from the updated stdlib/std.jsonnet.
  • Golden files: Updated to reflect shifted line numbers in error traces.

Test plan

  • Existing format tests continue to pass (go test ./... passes)
  • Verified %d, %f, %x, %o, %e, %g with boolean values produce correct output
  • Verified %s with boolean values still returns string representation

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/1
before processing numeric conversion codes, matching Python's behavior.

Added stdlib/std.jsonnet with the boolean coercion fix in format_code().
Regenerated astgen/stdast.go from the updated std.jsonnet.
Updated golden files to reflect shifted line numbers in error traces.
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