Skip to content

Commit bdd2bcb

Browse files
committed
Fix commas ending up dangling on separate lines in some cases
Close #51
1 parent f51e61a commit bdd2bcb

3 files changed

Lines changed: 52 additions & 0 deletions

File tree

src/formatter.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ impl Formatter {
134134
fn postprocess(&mut self) -> &mut Self {
135135
self.clean_up_lines_with_only_whitespace()
136136
.fix_dangling_semicolons()
137+
.fix_dangling_commas()
137138
.remove_trailing_commas_from_preload()
138139
.postprocess_tree_sitter()
139140
}
@@ -240,6 +241,25 @@ impl Formatter {
240241
self
241242
}
242243

244+
/// This function fixes commas that end up on their own line with indentation
245+
/// by moving them to the end of the previous line. This commonly happens
246+
/// with lambdas in data structures like arrays or function arguments.
247+
#[inline(always)]
248+
fn fix_dangling_commas(&mut self) -> &mut Self {
249+
// This targets cases where a comma is on its own line with only
250+
// whitespace before it instead of being at the end of the previous
251+
// line
252+
// Pattern: capture content before newline, then newline + whitespace + comma
253+
let re = RegexBuilder::new(r"([^\n\r])\n\s+,")
254+
.multi_line(true)
255+
.build()
256+
.expect("dangling comma regex should compile");
257+
if let Cow::Owned(replaced) = re.replace_all(&self.content, "$1,") {
258+
self.content = replaced;
259+
}
260+
self
261+
}
262+
243263
/// This function removes trailing commas from preload function calls.
244264
/// The GDScript parser doesn't support trailing commas in preload calls,
245265
/// but our formatter might add them for multi-line calls.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
tween.tween_method(
2+
func(x: float) -> void:
3+
if x <= 1.0:
4+
print(x),
5+
0.0,
6+
1.0,
7+
0.37,
8+
)
9+
10+
var g: Array[Callable] = [
11+
func():
12+
pass,
13+
func():
14+
pass,
15+
]
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
tween.tween_method(func(x: float) -> void:
2+
if x <= 1.0:
3+
print(x)
4+
,
5+
0.0,
6+
1.0,
7+
0.37
8+
)
9+
10+
var g: Array[Callable] = [
11+
func():
12+
pass
13+
,
14+
func():
15+
pass
16+
,
17+
]

0 commit comments

Comments
 (0)