Skip to content

formatter: preserve [expr] key syntax in object comprehensions#880

Open
ricardbejarano wants to merge 1 commit into
google:masterfrom
bejaratommy:fix/object-comp-literal-key-formatting
Open

formatter: preserve [expr] key syntax in object comprehensions#880
ricardbejarano wants to merge 1 commit into
google:masterfrom
bejaratommy:fix/object-comp-literal-key-formatting

Conversation

@ricardbejarano

Copy link
Copy Markdown

Fixes #879.

Problem

jsonnetfmt was producing invalid output for object comprehensions with literal computed keys. Given:

{['0']: 1 for x in [1]}

the formatter would output:

{ '0': 1 for x in [1] }

which fails to parse — the evaluator rejects it with:

Object comprehensions can only have [e] fields

The ['literal'] -> literal simplification applied by PrettyFieldNames is correct for regular objects (since {['a']: 1} == {a: 1}), but object comprehensions require the [expr] key syntax, so the rewrite must not be applied there.

Fix

Override ObjectComp in PrettyFieldNames to set a flag while traversing comprehension fields, and skip the key-kind rewrite when that flag is set. The field's value expression is still visited normally.

A golden test case is added to cover the bug.

The PrettyFieldNames formatter pass was incorrectly simplifying
computed string keys inside object comprehensions, e.g. turning
['0'] into '0'. While this rewrite is valid in regular objects
(where {['a']: 1} == {a: 1}), object comprehensions require
the [expr] key syntax; the simplified form is rejected by the parser.

The fix tracks whether we are currently visiting an ObjectComp
and, if so, skips the key-kind rewrite while still recursing into
the field's value expression.

Fixes google#879

Signed-off-by: bejaratommy <tommy@bejara.net>
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.

jsonnetfmt produces invalid output for object comprehensions with literal computed keys

2 participants