Skip to content

Commit

Permalink
vfmt: fix the formatting of comments after const declarations (#20005)
Browse files Browse the repository at this point in the history
  • Loading branch information
StunxFS committed Nov 27, 2023
1 parent 5283f19 commit 2964855
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
5 changes: 3 additions & 2 deletions vlib/v/fmt/fmt.v
Expand Up @@ -913,7 +913,7 @@ pub fn (mut f Fmt) const_decl(node ast.ConstDecl) {
} else {
ast.Node(ast.NodeError{})
}
for _, field in node.fields {
for fidx, field in node.fields {
if field.comments.len > 0 {
if f.should_insert_newline_before_node(ast.Expr(field.comments[0]), prev_field) {
f.writeln('')
Expand All @@ -936,7 +936,8 @@ pub fn (mut f Fmt) const_decl(node ast.ConstDecl) {
f.write('= ')
f.expr(field.expr)
f.comments(field.end_comments, same_line: true)
if node.is_block && field.end_comments.len == 0 {
if node.is_block && fidx < node.fields.len - 1 && node.fields.len > 1 {
// old style grouped consts, converted to the new style ungrouped const
f.writeln('')
} else {
// Write out single line comments after const expr if present
Expand Down
6 changes: 6 additions & 0 deletions vlib/v/fmt/tests/consts_expected.vv
Expand Up @@ -25,6 +25,12 @@ const i_am_a_very_long_constant_name_so_i_stand_alone_and_my_length_is_over_90_c

pub const i_am_pub_const = true

const abc = 1 // abc

const def = 2 // def

const ghi = 3 // ghi

fn main() {
a := [
[3, 5, 6],
Expand Down
8 changes: 7 additions & 1 deletion vlib/v/fmt/tests/consts_input.vv
Expand Up @@ -17,7 +17,7 @@ another_const = ['a', 'b'
]
multiline_const = [
'first line', 'second line','third line',
'fourth line']
'fourth line']
)

const (
Expand All @@ -28,6 +28,12 @@ pub const (
i_am_pub_const=true
)

const (
abc = 1 // abc
def = 2 // def
ghi = 3 // ghi
)

fn main() {
a := [
[3,
Expand Down
6 changes: 6 additions & 0 deletions vlib/v/parser/parser.v
Expand Up @@ -3838,6 +3838,9 @@ fn (mut p Parser) const_decl() ast.ConstDecl {
p.vet_notice('use a fixed array, instead of a dynamic one', pos.line_nr, vet.FixKind.unknown,
.default)
}
if is_block {
end_comments << p.eat_comments(same_line: true)
}
field := ast.ConstField{
name: full_name
mod: p.mod
Expand All @@ -3851,6 +3854,9 @@ fn (mut p Parser) const_decl() ast.ConstDecl {
fields << field
p.table.global_scope.register(field)
comments = []
if is_block {
end_comments = []
}
if !is_block {
break
}
Expand Down

0 comments on commit 2964855

Please sign in to comment.