Skip to content

Refactor write_snippet #482

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

Merged
merged 1 commit into from
Oct 17, 2015
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
41 changes: 10 additions & 31 deletions src/missed_spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,43 +59,22 @@ impl<'a> FmtVisitor<'a> {
let span = codemap::mk_sp(start, end);
let snippet = self.snippet(span);

self.write_snippet(&snippet, true, &process_last_snippet);
self.write_snippet(&snippet, &process_last_snippet);
}

fn write_snippet<F: Fn(&mut FmtVisitor, &str, &str)>(&mut self,
snippet: &str,
last_snippet: bool,
process_last_snippet: F) {
// Trim whitespace from the right hand side of each line.
// Annoyingly, the library functions for splitting by lines etc. are not
// quite right, so we must do it ourselves.
let mut line_start = 0;
let mut last_wspace = None;
for (i, c) in snippet.char_indices() {
if c == '\n' {
if let Some(lw) = last_wspace {
self.buffer.push_str(&snippet[line_start..lw]);
self.buffer.push_str("\n");
} else {
self.buffer.push_str(&snippet[line_start..i + 1]);
}

line_start = i + 1;
last_wspace = None;
} else {
if c.is_whitespace() {
if last_wspace.is_none() {
last_wspace = Some(i);
}
} else {
last_wspace = None;
}
}
}
if last_snippet {
process_last_snippet(self, &snippet[line_start..], snippet);
let mut lines: Vec<&str> = snippet.lines().collect();
let last_snippet = if snippet.ends_with("\n") {
""
} else {
self.buffer.push_str(&snippet[line_start..]);
lines.pop().unwrap()
};
for line in lines.iter() {
self.buffer.push_str(line.trim_right());
self.buffer.push_str("\n");
}
process_last_snippet(self, &last_snippet, snippet);
}
}