Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions formatter/testdata/object_comp_literal_key.fmt.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ ['0']: 1 for x in [1] }
1 change: 1 addition & 0 deletions formatter/testdata/object_comp_literal_key.jsonnet
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ ['0']: 1 for x in [1] }
15 changes: 15 additions & 0 deletions internal/formatter/pretty_field_names.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
// PrettyFieldNames forces minimal syntax with field lookups and definitions
type PrettyFieldNames struct {
pass.Base
insideObjectComp bool
}

// Index prettifies the definitions.
Expand All @@ -44,8 +45,22 @@ func (c *PrettyFieldNames) Index(p pass.ASTPass, index *ast.Index, ctx pass.Cont
c.Base.Index(p, index, ctx)
}

// ObjectComp traverses an object comprehension, skipping field key simplification
// since object comprehensions require the [expr] key syntax.
func (c *PrettyFieldNames) ObjectComp(p pass.ASTPass, node *ast.ObjectComp, ctx pass.Context) {
prev := c.insideObjectComp
c.insideObjectComp = true
c.Base.ObjectComp(p, node, ctx)
c.insideObjectComp = prev
}

// ObjectField prettifies the definitions.
func (c *PrettyFieldNames) ObjectField(p pass.ASTPass, field *ast.ObjectField, ctx pass.Context) {
if c.insideObjectComp {
// Object comprehensions require [expr] key syntax; do not simplify the key.
c.Base.ObjectField(p, field, ctx)
return
}
if field.Kind == ast.ObjectFieldExpr {
// First try ["foo"] -> "foo".
lit, ok := field.Expr1.(*ast.LiteralString)
Expand Down