diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index cf180af7e5..40a4cbdf8a 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -1380,7 +1380,8 @@ pub struct ParExpr { pub: pos token.Pos pub mut: - expr Expr + expr Expr + comments []Comment } [minify] diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index b126e3c111..72fd5f5523 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -1393,7 +1393,7 @@ pub fn (mut f Fmt) return_stmt(node ast.Return) { f.comments(pre_comments) f.write(' ') } - if expr is ast.ParExpr { + if expr is ast.ParExpr && expr.comments.len == 0 { f.expr(expr.expr) } else { f.expr(expr) @@ -2698,12 +2698,22 @@ pub fn (mut f Fmt) par_expr(node ast.ParExpr) { for mut expr is ast.ParExpr { expr = expr.expr } - requires_paren := expr !is ast.Ident + requires_paren := expr !is ast.Ident || node.comments.len > 0 if requires_paren { f.par_level++ f.write('(') } + pre_comments := node.comments.filter(it.pos.pos < expr.pos().pos) + post_comments := node.comments[pre_comments.len..] + if pre_comments.len > 0 { + f.comments(pre_comments) + f.write(' ') + } f.expr(expr) + if post_comments.len > 0 { + f.comments(post_comments) + f.write(' ') + } if requires_paren { f.par_level-- f.write(')') diff --git a/vlib/v/fmt/tests/return_with_comments_expected.vv b/vlib/v/fmt/tests/return_with_comments_expected.vv new file mode 100644 index 0000000000..ccee188537 --- /dev/null +++ b/vlib/v/fmt/tests/return_with_comments_expected.vv @@ -0,0 +1,22 @@ +fn foo1() int { + return (0 /* some comment */ ) +} + +fn foo2() int { + return ( /* some comment */ 0) +} + +fn foo3() int { + return ( /* some comment1 */ 0 /* some comment2 */ ) +} + +fn foo4() int { + return ( /* some comment1 */ /* some comment2 */ 0) +} + +fn foo5() int { + return ( /* some comment1 */ /* some comment2 */ 0 /* some comment3 */ /* some comment4 */ ) +} + +fn main() { +} diff --git a/vlib/v/fmt/tests/return_with_comments_input.vv b/vlib/v/fmt/tests/return_with_comments_input.vv new file mode 100644 index 0000000000..a4a822ff90 --- /dev/null +++ b/vlib/v/fmt/tests/return_with_comments_input.vv @@ -0,0 +1,22 @@ +fn foo1() int { + return (0/* some comment */) +} + +fn foo2() int { + return (/* some comment */0) +} + +fn foo3() int { + return (/* some comment1 */ 0/* some comment2 */) +} + +fn foo4() int { + return (/* some comment1 */ /* some comment2 */0) +} + +fn foo5() int { + return (/* some comment1 */ /* some comment2 */0/* some comment3 */ /* some comment4 */) +} + +fn main() { +} diff --git a/vlib/v/parser/expr.v b/vlib/v/parser/expr.v index 091dc304db..2d1b9a62cf 100644 --- a/vlib/v/parser/expr.v +++ b/vlib/v/parser/expr.v @@ -147,11 +147,14 @@ fn (mut p Parser) check_expr(precedence int) !ast.Expr { .lpar { mut pos := p.tok.pos() p.check(.lpar) + mut comments := p.eat_comments() node = p.expr(0) + comments << p.eat_comments() p.check(.rpar) node = ast.ParExpr{ expr: node pos: pos.extend(p.prev_tok.pos()) + comments: comments } } .key_if {