Skip to content

Commit c2326d4

Browse files
committed
Fix handling of line comments in multi-line statements.
1 parent ddff2bc commit c2326d4

File tree

5 files changed

+22
-1
lines changed

5 files changed

+22
-1
lines changed

hcl/parser/parser.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,12 @@ func (p *Parser) objectItem() (*ast.ObjectItem, error) {
205205
}
206206
}
207207

208+
// key=#comment
209+
// val
210+
if p.lineComment != nil {
211+
o.LineComment, p.lineComment = p.lineComment, nil
212+
}
213+
208214
// do a look-ahead for line comment
209215
p.scan()
210216
if len(keys) > 0 && o.Val.Pos().Line == keys[0].Pos().Line && p.lineComment != nil {

hcl/printer/nodes.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,14 @@ func (p *printer) objectItem(o *ast.ObjectItem) []byte {
252252
}
253253
}
254254

255+
// If key and val are on different lines, treat line comments like lead comments.
256+
if o.LineComment != nil && o.Val.Pos().Line != o.Keys[0].Pos().Line {
257+
for _, comment := range o.LineComment.List {
258+
buf.WriteString(comment.Text)
259+
buf.WriteByte(newline)
260+
}
261+
}
262+
255263
for i, k := range o.Keys {
256264
buf.WriteString(k.Token.Text)
257265
buf.WriteByte(blank)
@@ -265,7 +273,7 @@ func (p *printer) objectItem(o *ast.ObjectItem) []byte {
265273

266274
buf.Write(p.output(o.Val))
267275

268-
if o.Val.Pos().Line == o.Keys[0].Pos().Line && o.LineComment != nil {
276+
if o.LineComment != nil && o.Val.Pos().Line == o.Keys[0].Pos().Line {
269277
buf.WriteByte(blank)
270278
for _, comment := range o.LineComment.List {
271279
buf.WriteString(comment.Text)

hcl/printer/testdata/comment.golden

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,6 @@ variable = {
3434
foo {
3535
bar = "fatih" // line comment 2
3636
} // line comment 3
37+
38+
// comment
39+
multiline = "assignment"

hcl/printer/testdata/comment.input

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,5 @@ foo {
3535
bar = "fatih" // line comment 2
3636
} // line comment 3
3737

38+
multiline = // comment
39+
"assignment"

hcl/printer/testdata/comment_crlf.input

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,5 @@ foo {
3535
bar = "fatih" // line comment 2
3636
} // line comment 3
3737

38+
multiline = // comment
39+
"assignment"

0 commit comments

Comments
 (0)