Skip to content

Commit 62ec461

Browse files
committed
refactor(formatting): Allow ' if contains "
1 parent 644643b commit 62ec461

File tree

2 files changed

+22
-29
lines changed

2 files changed

+22
-29
lines changed

src/format.rs

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,9 @@ fn traverse(
189189
return node.end_position();
190190
}
191191

192-
node.child_by_field_name("rhs")
192+
field_optional(node, "rhs")
193193
.map(|rhs| rhs.end_position())
194-
.or_else(|| {
195-
node.child_by_field_name("operator")
196-
.map(|operator| operator.end_position())
197-
})
194+
.or_else(|| field_optional(node, "operator").map(|operator| operator.end_position()))
198195
// note: this case is unexpected
199196
.unwrap_or_else(|| node.end_position())
200197
};
@@ -944,26 +941,22 @@ fn traverse(
944941
})?;
945942
}
946943
"string" => {
947-
out.push('"');
948-
tree::for_each_child(cursor, |_, child, field_name, cursor| match field_name {
949-
None => match child.kind() {
950-
"\"" => Ok(()),
951-
"\'" => Ok(()),
952-
_ => unreachable!(),
953-
},
954-
Some("content") => fmt(out, cursor),
955-
Some(_) => unreachable!(),
956-
})?;
957-
out.push('"');
958-
}
959-
"string_content" => {
960-
let mut last_was_escape = false;
961-
for char in get_raw(node).chars() {
962-
match char {
963-
'"' if !last_was_escape => out.push_str("\\\""),
964-
_ => out.push(char),
944+
if let Some(content) = field_optional(node, "content") {
945+
let raw = get_raw(content);
946+
let mut all_quotes_escaped = true;
947+
let mut prev_was_escape = false;
948+
for char in raw.chars() {
949+
if char == '"' {
950+
all_quotes_escaped &= prev_was_escape;
951+
}
952+
prev_was_escape = char == '\\' && !prev_was_escape;
965953
}
966-
last_was_escape = char == '\\' && !last_was_escape;
954+
let quote = if all_quotes_escaped { '"' } else { '\'' };
955+
out.push(quote);
956+
out.push_str(&raw);
957+
out.push(quote);
958+
} else {
959+
out.push_str(r#""""#);
967960
}
968961
}
969962
"unary_operator" => {
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
---
2-
source: src/format.rs
3-
expression: "format_str(indoc!\n{\n r#\"\n '\"foo\"'\n \"\\\"foo\\\"\"\n '\\\"foo\"'\n '\\\\\"foo\\\\\"'\n \"\\\\\\\"foo\\\\\\\"\"\n \"#\n}).unwrap()"
2+
source: tests/test_format.rs
3+
expression: "format_str(indoc!\n{\n r#\"\n '\"foo\"'\n \"\\\"foo\\\"\"\n '\\\"foo\"'\n '\\\\\"foo\\\\\"'\n \"\\\\\\\"foo\\\\\\\"\"\n \"#\n}).unwrap()"
44
---
5+
'"foo"'
56
"\"foo\""
6-
"\"foo\""
7-
"\"foo\""
8-
"\\\"foo\\\""
7+
'\"foo"'
8+
'\\"foo\\"'
99
"\\\"foo\\\""

0 commit comments

Comments
 (0)