Skip to content

Commit

Permalink
cue/format: ensure a newline after every comment
Browse files Browse the repository at this point in the history
This is similar to the nooverride whiteSpace flag,
but only enforces the newline whitespace token to be printed.

Fixes #2567.

Co-authored-by: Daniel Martí <mvdan@mvdan.cc>
Co-authored-by: Noam Dolovich <noam.tzvi.dolovich@gmail.com>
Signed-off-by: Noam Dolovich <noam.tzvi.dolovich@gmail.com>
Signed-off-by: Daniel Martí <mvdan@mvdan.cc>
Change-Id: I83bebcca9aeba14f84cbcf4c4befa0677da3fb0f
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1195628
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>
Unity-Result: CUE porcuepine <cue.porcuepine@gmail.com>
  • Loading branch information
mvdan and NoamTD committed Jun 6, 2024
1 parent e09cb31 commit b423a27
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions cue/format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ func (f *formatter) printComment(cg *ast.CommentGroup) {
f.Print(c.Slash)
f.Print(c)
if isEnd {
f.printingComment = true
f.Print(newline)
if cg.Doc {
f.Print(nooverride)
Expand Down
10 changes: 10 additions & 0 deletions cue/format/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ type printer struct {
spaceBefore bool
prevLbraceOnLine bool // true if a '{' has been written on the current line

// TODO(mvdan): This is similar to nooverride but used only for comments,
// to ensure that we always print a newline after them.
// We should fix our logic with whiteSpace instead, but for now this ensures
// we don't break the syntax by omitting the newline after a comment.
printingComment bool

errs errors.Error
}

Expand Down Expand Up @@ -231,6 +237,9 @@ func (p *printer) Print(v interface{}) {
case token.NewSection:
requested |= newsection
}
if p.printingComment {
requested |= newline
}
p.writeWhitespace(requested)
p.allowed = 0
p.requested = 0
Expand All @@ -247,6 +256,7 @@ func (p *printer) Print(v interface{}) {
p.writeWhitespace(p.allowed)
p.allowed = 0
p.requested = 0
p.printingComment = false
p.writeString(data, isLit)
p.allowed = nextWS
_ = impliedComma // TODO: delay comment printings
Expand Down
9 changes: 9 additions & 0 deletions cue/format/testdata/comments.golden
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,12 @@ funcArg3: foo(
)

// comment including some tabs

// issue #2567
foo: [
bar["baz"], //some comment
]

[
if true {}, // inline comment
]
10 changes: 10 additions & 0 deletions cue/format/testdata/comments.input
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,13 @@ funcArg3: foo(
)

// comment including some tabs


// issue #2567
foo: [
bar["baz"], //some comment
]

[
if true // inline comment
{}]

0 comments on commit b423a27

Please sign in to comment.