Skip to content

Commit 5a95298

Browse files
committed
feat(fmt): Allow more comment positions in binary operator
1 parent 947d638 commit 5a95298

File tree

2 files changed

+55
-6
lines changed

2 files changed

+55
-6
lines changed

src/format.rs

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -438,26 +438,45 @@ fn traverse(
438438
}
439439
"binary_operator" => {
440440
handles_comments = true;
441+
let lhs = field("lhs")?;
442+
let operator = field("operator")?;
443+
let rhs = field("rhs")?;
444+
441445
let mut cursor = node.walk();
442446
let comments = node
443447
.children(&mut cursor)
444448
.filter(|node| node.kind() == "comment")
449+
.collect::<Vec<Node>>();
450+
let indent = format!("{line_ending}{}", " ".repeat(config.spaces));
451+
let first_comment_sep = comments
452+
.first()
453+
.map(|comment| {
454+
if operator.end_position().row == comment.start_position().row {
455+
" "
456+
} else {
457+
indent.as_str()
458+
}
459+
})
460+
.unwrap_or(" ");
461+
let comments_fmt = comments
462+
.into_iter()
445463
.map(fmt)
446464
.collect::<Result<Vec<String>, FormatError>>()?
447-
.join(&format!("{line_ending}{}", " ".repeat(config.spaces)));
465+
.join(&indent);
448466

449-
let lhs = field("lhs")?;
450-
let operator = field("operator")?;
451-
let rhs = field("rhs")?;
452467
let is_multiline = lhs.end_position().row != rhs.start_position().row;
453468
let has_spacing = operator.kind() == ":";
454469
format!(
455470
"{}{}{}{}{}{}{}",
456471
fmt(lhs)?,
457472
if has_spacing { "" } else { " " },
458473
fmt(operator)?,
459-
if comments.is_empty() { "" } else { " " },
460-
comments,
474+
if comments_fmt.is_empty() {
475+
""
476+
} else {
477+
first_comment_sep
478+
},
479+
comments_fmt,
461480
if is_multiline {
462481
line_ending
463482
} else if has_spacing {
@@ -1045,6 +1064,20 @@ mod test {
10451064
baz |>
10461065
qux
10471066
"#};
1067+
assert_fmt! {r#"
1068+
foo |>
1069+
# something about bar
1070+
bar |>
1071+
# something about baz
1072+
baz
1073+
foo |># 1
1074+
# 2
1075+
bar |> # 3
1076+
# 4
1077+
# 5
1078+
# 6
1079+
baz
1080+
"#};
10481081
}
10491082

10501083
#[test]
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
source: src/format.rs
3+
expression: "format_str(indoc!\n{\n r#\"\n foo |>\n # something about bar\n bar |>\n # something about baz\n baz\n foo |># 1\n # 2\n bar |> # 3\n # 4\n # 5\n # 6\n baz\n \"#\n}).unwrap()"
4+
---
5+
foo |>
6+
# something about bar
7+
bar |>
8+
# something about baz
9+
baz
10+
foo |> # 1
11+
# 2
12+
bar |> # 3
13+
# 4
14+
# 5
15+
# 6
16+
baz

0 commit comments

Comments
 (0)