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: Handle multi-byte utf8 characters in formatter #6118

Merged
merged 9 commits into from
Sep 24, 2024
17 changes: 15 additions & 2 deletions tooling/nargo_fmt/src/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

pub(crate) fn slice(&self, span: impl Into<Span>) -> &'me str {
let span = span.into();
&self.source[span.start() as usize..span.end() as usize]
str_slice(self.source, span.start() as usize, span.end() as usize)
}

pub(crate) fn span_after(&self, span: impl Into<Span>, token: Token) -> Span {
Expand Down Expand Up @@ -180,7 +180,7 @@

pub(crate) fn format_comment_in_block(&mut self, slice: &str) -> (String, u32) {
let mut result = String::new();
let comments = Lexer::new(slice).skip_comments(false).skip_whitespaces(false).flatten();

Check warning on line 183 in tooling/nargo_fmt/src/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)

let indent = self.indent.to_string();
for comment in comments {
Expand All @@ -188,7 +188,7 @@

match comment.token() {
Token::LineComment(_, _) | Token::BlockComment(_, _) => {
let comment = &slice[span.start() as usize..span.end() as usize];
let comment = str_slice(slice, span.start() as usize, span.end() as usize);
if result.ends_with('\n') {
result.push_str(&indent);
} else if !self.at_start() {
Expand All @@ -196,10 +196,10 @@
}
result.push_str(comment);
}
Token::Whitespace(whitespaces) => {

Check warning on line 199 in tooling/nargo_fmt/src/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
let mut visitor = self.fork();
if whitespaces.contains('\n') {

Check warning on line 201 in tooling/nargo_fmt/src/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
visitor.push_vertical_spaces(whitespaces.trim_matches(' '));

Check warning on line 202 in tooling/nargo_fmt/src/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
result.push_str(&visitor.finish());
}
}
Expand Down Expand Up @@ -247,6 +247,19 @@
}
}

pub(crate) fn str_slice(s: &str, start: usize, end: usize) -> &str {
&s[start..ceil_char_boundary(s, end)]
}

pub(crate) fn ceil_char_boundary(s: &str, byte_index: usize) -> usize {
for i in byte_index..s.len() {
if s.is_char_boundary(i) {
return i;
}
}
s.len()
}

#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Indent {
block_indent: usize,
Expand Down
Loading