Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(formatter): escape double quotes when printing formatter IR #3036

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion crates/biome_formatter/src/format_element/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,35 @@ impl Format<IrFormatContext> for &[FormatElement] {
FormatElement::Space | FormatElement::HardSpace => {
write!(f, [text(" ")])?;
}
element if element.is_text() => f.write_element(element.clone())?,
element if element.is_text() => {
// escape quotes
let new_element = match element {
// except for static text because source_position is unknown
FormatElement::StaticText { .. } => element.clone(),
FormatElement::DynamicText {
text,
source_position,
} => {
let text = text.to_string().replace('"', "\\\"");
FormatElement::DynamicText {
text: text.into(),
source_position: *source_position,
}
}
FormatElement::LocatedTokenText {
slice,
source_position,
} => {
let text = slice.to_string().replace('"', "\\\"");
FormatElement::DynamicText {
text: text.into(),
source_position: *source_position,
}
}
_ => unreachable!(),
};
f.write_element(new_element)?;
}
_ => unreachable!(),
}

Expand Down Expand Up @@ -710,6 +738,10 @@ impl FormatElements for [FormatElement] {

#[cfg(test)]
mod tests {
use biome_js_syntax::JsSyntaxKind;
use biome_js_syntax::JsSyntaxToken;
use biome_rowan::TextSize;

use crate::prelude::*;
use crate::SimpleFormatContext;
use crate::{format, format_args, write};
Expand Down Expand Up @@ -837,4 +869,24 @@ mod tests {
]"#
);
}

#[test]
fn escapes_quotes() {
let token = JsSyntaxToken::new_detached(JsSyntaxKind::JS_STRING_LITERAL, "\"bar\"", [], []);
let token_text = FormatElement::LocatedTokenText {
source_position: TextSize::default(),
slice: token.token_text(),
};

let mut document = Document::from(vec![
FormatElement::DynamicText {
text: "\"foo\"".into(),
source_position: TextSize::default(),
},
token_text,
]);
document.propagate_expand();

assert_eq!(&std::format!("{document}"), r#"["\"foo\"\"bar\""]"#);
}
}