ast, parser, fmt: fix formatting return with comments in parentheses (#19188)

This commit is contained in:
yuyi 2023-08-21 15:51:40 +08:00 committed by GitHub
parent c3be85e87d
commit 01cb30c023
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 61 additions and 3 deletions

View File

@ -1380,7 +1380,8 @@ pub struct ParExpr {
pub:
pos token.Pos
pub mut:
expr Expr
expr Expr
comments []Comment
}
[minify]

View File

@ -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(')')

View File

@ -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() {
}

View File

@ -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() {
}

View File

@ -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 {