Playground: Fix escaped quotes handling (#5906)

Co-authored-by: konsti <konstin@mailbox.org>
This commit is contained in:
Micha Reiser 2023-07-20 11:25:27 +02:00 committed by GitHub
parent 9e32585cb1
commit 029fe05a5f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 1 deletions

View file

@ -255,11 +255,35 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
in_text = true;
fn write_escaped(
element: &FormatElement,
f: &mut Formatter<IrFormatContext>,
) -> FormatResult<()> {
let text = match element {
FormatElement::StaticText { text } => text,
FormatElement::DynamicText { text } => text.as_ref(),
FormatElement::SourceCodeSlice { slice, .. } => {
slice.text(f.context().source_code())
}
_ => unreachable!(),
};
if text.contains('"') {
f.write_element(FormatElement::DynamicText {
text: text.replace('"', r#"\""#).into(),
})
} else {
f.write_element(element.clone())
}
}
match element {
FormatElement::Space => {
write!(f, [text(" ")])?;
}
element if element.is_text() => f.write_element(element.clone())?,
element if element.is_text() => {
write_escaped(element, f)?;
}
_ => unreachable!(),
}
@ -787,6 +811,22 @@ mod tests {
);
}
#[test]
fn escapes_quotes() {
let formatted = format!(
SimpleFormatContext::default(),
[text(r#""""Python docstring""""#)]
)
.unwrap();
let document = formatted.into_document();
assert_eq!(
&std::format!("{}", document.display(SourceCode::default())),
r#"["\"\"\"Python docstring\"\"\""]"#
);
}
#[test]
fn display_elements_with_source_text_slice() {
let source_code = "Some longer content\nThat should ultimately break";

View file

@ -596,6 +596,7 @@ function defineRustPythonAstLanguage(monaco: Monaco) {
],
string: [
[/[^\\"]+/, "string"],
[/\\[\\"]/, "string.escape"],
[/"/, { token: "string.quote", bracket: "@close", next: "@pop" }],
],
},
@ -650,6 +651,7 @@ function defineRustPythonTokensLanguage(monaco: Monaco) {
],
string: [
[/[^\\"]+/, "string"],
[/\\[\\"]/, "string.escape"],
[/"/, { token: "string.quote", bracket: "@close", next: "@pop" }],
],
},
@ -695,6 +697,7 @@ function defineFirLanguage(monaco: Monaco) {
],
string: [
[/[^\\"]+/, "string"],
[/\\[\\"]/, "string.escape"],
[/"/, { token: "string.quote", bracket: "@close", next: "@pop" }],
],
},