Make sure to escape formatting of char literals

Closes #4682
This commit is contained in:
Ayaz Hafiz 2022-12-05 14:07:30 -06:00
parent 3399fe10a0
commit aab509c5c1
No known key found for this signature in database
GPG key ID: 0E2A37416A25EF58
3 changed files with 29 additions and 15 deletions

View file

@ -298,17 +298,7 @@ impl<'a> Formattable for Expr<'a> {
}
SingleQuote(string) => {
buf.indent(indent);
buf.push('\'');
for c in string.chars() {
if c == '"' {
buf.push_char_literal('"')
} else {
for escaped in c.escape_default() {
buf.push_char_literal(escaped);
}
}
}
buf.push('\'');
format_sq_literal(buf, string);
}
&NonBase10Int {
base,
@ -438,6 +428,20 @@ impl<'a> Formattable for Expr<'a> {
}
}
pub(crate) fn format_sq_literal(buf: &mut Buf, s: &str) {
buf.push('\'');
for c in s.chars() {
if c == '"' {
buf.push_char_literal('"')
} else {
for escaped in c.escape_default() {
buf.push_char_literal(escaped);
}
}
}
buf.push('\'');
}
fn starts_with_newline(expr: &Expr) -> bool {
use roc_parse::ast::Expr::*;

View file

@ -1,5 +1,5 @@
use crate::annotation::{Formattable, Newlines, Parens};
use crate::expr::fmt_str_literal;
use crate::expr::{fmt_str_literal, format_sq_literal};
use crate::spaces::{fmt_comments_only, fmt_spaces, NewlineAt};
use crate::Buf;
use roc_parse::ast::{Base, CommentOrNewline, Pattern};
@ -155,9 +155,7 @@ impl<'a> Formattable for Pattern<'a> {
StrLiteral(literal) => fmt_str_literal(buf, *literal, indent),
SingleQuote(string) => {
buf.indent(indent);
buf.push('\'');
buf.push_str(string);
buf.push('\'');
format_sq_literal(buf, string);
}
Underscore(name) => {
buf.indent(indent);

View file

@ -5673,6 +5673,18 @@ mod test_fmt {
));
}
#[test]
fn format_char_pattern() {
expr_formats_same(indoc!(
r#"
when x is
' ' -> x
'\n' -> x
'\t' -> x
"#
));
}
#[test]
fn format_nested_pipeline() {
expr_formats_same(indoc!(