Skip to content

Commit

Permalink
fix(formatter): escape double quotes when printing formatter IR
Browse files Browse the repository at this point in the history
  • Loading branch information
dyc3 committed Jun 11, 2024
1 parent e3e93cc commit e352ec5
Showing 1 changed file with 53 additions and 1 deletion.
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\""]"#);
}
}

0 comments on commit e352ec5

Please sign in to comment.