Skip to content

Commit

Permalink
ast, parser, fmt: fix formatting return with comments in parentheses (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Aug 21, 2023
1 parent c3be85e commit 01cb30c
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 3 deletions.
3 changes: 2 additions & 1 deletion vlib/v/ast/ast.v
Expand Up @@ -1380,7 +1380,8 @@ pub struct ParExpr {
pub:
pos token.Pos
pub mut:
expr Expr
expr Expr
comments []Comment
}

[minify]
Expand Down
14 changes: 12 additions & 2 deletions vlib/v/fmt/fmt.v
Expand Up @@ -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)
Expand Down Expand Up @@ -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(')')
Expand Down
22 changes: 22 additions & 0 deletions 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() {
}
22 changes: 22 additions & 0 deletions 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() {
}
3 changes: 3 additions & 0 deletions vlib/v/parser/expr.v
Expand Up @@ -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 {
Expand Down

0 comments on commit 01cb30c

Please sign in to comment.