Skip to content

Commit

Permalink
fix: (formatter) correctly format quote delimiters (#6377)
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite authored Oct 29, 2024
1 parent 15c729a commit b42accf
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions tooling/nargo_fmt/src/formatter/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,24 @@ impl<'a, 'b> ChunkFormatter<'a, 'b> {
}

pub(super) fn format_quote(&mut self) -> ChunkGroup {
// A quote's prefix isn't captured in the token, so let's figure it out which one
// is it by looking at the source code.
let mut quote_source_code =
&self.source[self.token_span.start() as usize..self.token_span.end() as usize];

// Remove "quote" and any whitespace following it
quote_source_code = quote_source_code.strip_prefix("quote").unwrap();
quote_source_code = quote_source_code.trim_start();

// The first char is the delimiter
let delimiter_start = quote_source_code.chars().next().unwrap();
let delimiter_end = match delimiter_start {
'(' => ')',
'{' => '}',
'[' => ']',
_ => panic!("Unexpected delimiter: {}", delimiter_start),
};

// We use the current token rather than the Tokens we got from `Token::Quote` because
// the current token has whitespace and comments in it, while the one we got from
// the parser doesn't.
Expand All @@ -319,11 +337,13 @@ impl<'a, 'b> ChunkFormatter<'a, 'b> {

let mut group = ChunkGroup::new();
group.verbatim(self.chunk(|formatter| {
formatter.write("quote {");
formatter.write("quote");
formatter.write_space();
formatter.write(&delimiter_start.to_string());
for token in tokens.0 {
formatter.write_source_span(token.to_span());
}
formatter.write("}");
formatter.write(&delimiter_end.to_string());
}));
group
}
Expand Down Expand Up @@ -2045,6 +2065,13 @@ global y = 1;
assert_format(src, expected);
}

#[test]
fn format_quote_with_bracket_delimiter() {
let src = "global x = quote [ 1 2 3 $four $(five) ];";
let expected = "global x = quote [ 1 2 3 $four $(five) ];\n";
assert_format(src, expected);
}

#[test]
fn format_lambda_no_parameters() {
let src = "global x = | | 1 ;";
Expand Down

0 comments on commit b42accf

Please sign in to comment.