diff --git a/kclvm/ast_pretty/src/lib.rs b/kclvm/ast_pretty/src/lib.rs index b4074971e..5709f2dc6 100644 --- a/kclvm/ast_pretty/src/lib.rs +++ b/kclvm/ast_pretty/src/lib.rs @@ -245,6 +245,14 @@ impl<'p> Printer<'p> { match self.comments.pop_front() { Some(comment) => { self.writeln(&comment.node.text); + match self.comments.front() { + Some(next_comment) => { + if next_comment.line >= comment.line + 2 && count > 0 { + self.write_newline(); + } + } + None => {} + } } None => break, } diff --git a/kclvm/ast_pretty/src/node.rs b/kclvm/ast_pretty/src/node.rs index 3f4c7f21a..8328f81c7 100644 --- a/kclvm/ast_pretty/src/node.rs +++ b/kclvm/ast_pretty/src/node.rs @@ -39,6 +39,7 @@ impl<'p, 'ctx> MutSelfTypedResultWalker<'ctx> for Printer<'p> { if let Some(doc) = &module.doc { self.write(&doc.node); self.write_newline(); + self.write_newline(); } self.stmts(&module.body); @@ -993,9 +994,13 @@ impl<'p> Printer<'p> { // Do not format out user-reserved blank lines: which does not mean that to preserve all user-written blank lines. // For situations where there are more than two blank lines, we only keep one blank line. let need_newline = if let Some(prev_stmt) = prev_stmt { - stmt.line > 0 - && stmt.line >= prev_stmt.end_line + 2 - && !self.has_comments_on_node(stmt) + if stmt.line > prev_stmt.end_line + 2 { + true + } else if stmt.line == prev_stmt.end_line + 2 { + stmt.line > 0 && !self.has_comments_on_node(stmt) + } else { + false + } } else { false }; diff --git a/kclvm/ast_pretty/src/test_data/codelayout.output b/kclvm/ast_pretty/src/test_data/codelayout.output index 2fcf3afca..8cc20e9fb 100644 --- a/kclvm/ast_pretty/src/test_data/codelayout.output +++ b/kclvm/ast_pretty/src/test_data/codelayout.output @@ -1,6 +1,7 @@ """ Module documents """ + import math as alias_math schema Person(Base): @@ -111,6 +112,7 @@ joined_data_3 = '''\ joined_data_4 = '''\ \${CC} ''' + # Member access and index assign targets a[0].b -= 1 a.b[0] += 1 diff --git a/kclvm/ast_pretty/src/test_data/comment.input b/kclvm/ast_pretty/src/test_data/comment.input index 7052c4f7a..36d6f1ced 100644 --- a/kclvm/ast_pretty/src/test_data/comment.input +++ b/kclvm/ast_pretty/src/test_data/comment.input @@ -77,4 +77,10 @@ data = [ # Comment One 2 # Comment Five # Comment Six *[3, 4] # Comment Seven -] \ No newline at end of file +] + +# This is a comment +foo = "bar" + +# This is another comment +fizz = "bazz" diff --git a/kclvm/ast_pretty/src/test_data/comment.output b/kclvm/ast_pretty/src/test_data/comment.output index 5547687b3..68f5cb611 100644 --- a/kclvm/ast_pretty/src/test_data/comment.output +++ b/kclvm/ast_pretty/src/test_data/comment.output @@ -34,10 +34,13 @@ appConfiguration = AppConfiguration { name: "kusion_override" } # Comment Seven + # Comment Eight overQuota: True } + # Comment Nine + # Deprecated @Deprecated() schema Foo: @@ -91,3 +94,9 @@ data = [ # Comment Seven *[3, 4] ] + +# This is a comment +foo = "bar" + +# This is another comment +fizz = "bazz"